Arunava Paul
Arunava Paul

Reputation: 111

Request JS not giving the response

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

Answers (2)

Prakash Karena
Prakash Karena

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

Ankur Patel
Ankur Patel

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

Related Questions