Express and Nodejs: the best way to call an external API

I am new to Express and Nodejs. I am trying to call an external api to create data on a page. Is there a way to call an external api from an expression (I know I can use http moduel for this), but I want to confirm that this is the best way. Also, as soon as I get json back, how to pass it to the view.

Currently, I have made a workaround by simply loading the view (headers only) with an expression and making a jQuery ajax api call and populating the data.

+5
source share
2 answers

First of all, you need to call the external API inside the controller where you want to populate it. It will be best to use the http module, it is fairly easy to use http://nodejs.org/docs/v0.4.10/api/http.html#http.get . After you receive the data, you simply submit it for viewing as follows:

 http.get(options, function(data) { res.render('template', data); }); 
+4
source

I would write an object to hide the information about this data fetch (http requests) and make http calls using superagent (just because it's a good library).

That way you can:

  • Replace http requests later if you decide to use something else.
  • Hide details, for example, using node-async , as the monkey suggested.
+1
source

Source: https://habr.com/ru/post/1200431/


All Articles