Express js controller to get data from an api service and render the view
api, express, javascript, node.js
Solution
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.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.
Problem
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'} 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