Express和Nodejs:调用外部API的最佳方式 [英] Express and Nodejs : Best way to call an external API

查看:2372
本文介绍了Express和Nodejs:调用外部API的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Express和Nodejs的新手。我试图调用外部api来在页面上构建数据。有没有办法从表达本身调用外部api(我知道我可以使用http moduel来做到这一点),但想确认是最好的方法。此外,一旦我得到json,我如何将它传递给视图。

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.

现在我已经完成了一个解决方法,只需加载视图(只是标题)与快递和对api进行jquery ajax调用并填充数据。

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.

推荐答案

首先,你需要在控制器内部调用你的外部API你想要填充它的地方。最好的方法是使用 http 模块,这很容易使用 http://nodejs.org/docs/v0.4.10/api/http.html#http.get 。获取数据后,您只需将其传递给以下视图:

First 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.org/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);
});

这篇关于Express和Nodejs:调用外部API的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆