I have this system
我有这个系统
-
An API system which only response with JSON objects. Example: http://example.com/user/13 response: {name:'Aesome 1', age: '13'}
只响应JSON对象的API系统。示例:http://example.com/user/13 response: {name:'Aesome 1', age: '13'}
-
ExpressJS web app which creates the views and sends the views to the user.
ExpressJS web应用程序创建视图并将视图发送给用户。
Now what I need to do it to get the JSON object from the API and render a view in ExpressJS and then send to the client.
现在我需要做的是,从API获取JSON对象,用ExpressJS呈现视图,然后发送给客户端。
So I need to connect the ExpressJS app with this api system.
所以我需要把ExpressJS应用和这个api系统连接起来。
Please let me know how to do this.
请告诉我怎么做。
Thanks
谢谢
1 个解决方案
#1
4
You can use the request module for making api requests.
您可以使用请求模块进行api请求。
In your controller, do like this:
在你的控制器中,这样做:
var request = require('request');
function(req, res) {
request.get('http://example.com/user/13', function(err, response, body) {
if (!err && response.statusCode == 200) {
var locals = JSON.parse(body);
res.render('<YOUR TEMPLATE>', locals);
}
}
}
Note: If you really want to access api from server then use the sample, else you can fetch the result using ajax with less overhead of another server to server http call.
注意:如果您真的想从服务器访问api,那么使用这个示例,否则您可以使用ajax获取结果,而无需使用另一个服务器对服务器http调用的开销。
#1
4
You can use the request module for making api requests.
您可以使用请求模块进行api请求。
In your controller, do like this:
在你的控制器中,这样做:
var request = require('request');
function(req, res) {
request.get('http://example.com/user/13', function(err, response, body) {
if (!err && response.statusCode == 200) {
var locals = JSON.parse(body);
res.render('<YOUR TEMPLATE>', locals);
}
}
}
Note: If you really want to access api from server then use the sample, else you can fetch the result using ajax with less overhead of another server to server http call.
注意:如果您真的想从服务器访问api,那么使用这个示例,否则您可以使用ajax获取结果,而无需使用另一个服务器对服务器http调用的开销。