简体   繁体   English

Express js控制器从api服务获取数据并呈现视图

[英]Express js controller to get data from an api service and render the view

I have this system 我有这个系统

  1. An API system which only response with JSON objects. 仅响应JSON对象的API系统。 Example: http://example.com/user/13 response: {name:'Aesome 1', age: '13'} 示例: http//example.com/user/13回复:{name:'Aesome 1',年龄:'13'}

  2. 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 谢谢

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调用的开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM