admin管理员组文章数量:1330165
I am new to Express and Nodejs. I am trying to call an external api for building data on a page. Is there a way to call the external api from express itself (I know i can use http moduel to do this) but want to confirm is that the best way. Also once i get the json back how do i pass it to the view.
Right now i have done a workaround by just loading the view(just headers) with express and making an jquery ajax call to api and populate the data.
I am new to Express and Nodejs. I am trying to call an external api for building data on a page. Is there a way to call the external api from express itself (I know i can use http moduel to do this) but want to confirm is that the best way. Also once i get the json back how do i pass it to the view.
Right now i have done a workaround by just loading the view(just headers) with express and making an jquery ajax call to api and populate the data.
Share asked Aug 15, 2014 at 15:44 SaNmmSaNmm 2011 gold badge7 silver badges14 bronze badges 1- What API? Some APIs have specific libraries build for Node that you could use to connect to the service. Often you can just Google "$API Node API". – Adam Commented Aug 15, 2014 at 16:40
2 Answers
Reset to default 4First of all, you need to call your external API inside controller where you want to populate it. The best will be to use http
module, it is pretty easy to use http://nodejs/docs/v0.4.10/api/http.html#http.get . After you get data, you just pass it to view like this:
http.get(options, function(data) {
res.render('template', data);
});
I would write an object to hide the details of this data fetching (http requests) and make the http calls using superagent (just because it's a nice lib).
This way you can:
- Replace the http requests later if you decide to use something else.
- Hide details like using the node-async as monkeyinsight suggested.
本文标签: javascriptExpress and NodejsBest way to call an external APIStack Overflow
版权声明:本文标题:javascript - Express and Nodejs : Best way to call an external API - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742262480a2442773.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论