Reputation: 111
I'm trying to create a route in an express node app which will call an API and print the response. I'm using request.js to make the API call. I'm unable to get the response. What am I doing wrong?
var express = require('express');
const request = require('request');
const API_URL= 'http://api.airvisual.com/v2/nearest_city';
const API_KEY= 'XXXXXXXX';
var router = express.Router();
var URL;
router.get('/getDetails', function(req, res){
var options = {
url: API_URL + '?key='+ API_KEY,
method: 'GET',
qs: {
lat: req.query.lat,
long: req.query.lon
}
}
res.send(request.get(options).response);
});
module.exports = router;
Upvotes: 0
Views: 45
Reputation: 2595
Use request-promise Refer Document
//use npm install --save request-promise
var rp = require('request-promise');
router.get('/getDetails', function(req, res){
var options = {
url: API_URL + '?key='+ API_KEY,
method: 'GET',
qs: {
lat: req.query.lat,
long: req.query.lon
},
json : true
}
rp(options)
.then(function (parsedBody) {
// POST succeeded...
res.send() // send response data
})
.catch(function (err) {
// POST failed...
res.send() //send error data
});
});
Upvotes: 1
Reputation: 488
request js does not return promise, we have to use callback for that find more doc here https://www.npmjs.com/package/request
Upvotes: 0