admin管理员组

文章数量:1302361

I have this system

  1. An API system which only response with JSON objects. Example: response: {name:'Aesome 1', age: '13'}

  2. ExpressJS web app which creates the views and sends the views to the user.

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.

So I need to connect the ExpressJS app with this api system.

Please let me know how to do this.

Thanks

I have this system

  1. An API system which only response with JSON objects. Example: http://example./user/13 response: {name:'Aesome 1', age: '13'}

  2. ExpressJS web app which creates the views and sends the views to the user.

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.

So I need to connect the ExpressJS app with this api system.

Please let me know how to do this.

Thanks

Share Improve this question asked Jun 1, 2014 at 4:42 Hirantha DissanayakaHirantha Dissanayaka 731 gold badge1 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You can use the request module for making api requests.

In your controller, do like this:

var request = require('request');

function(req, res) {
    request.get('http://example./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.

本文标签: javascriptExpress js controller to get data from an api service and render the viewStack Overflow