I am trying to send a request to an API which returns JSON and then show that request in my own url but when I runs this code it shows that there's respond from API on the console but it can't send it to document usisng res.send I need some help to know where can I send this to the document out not just in the console. One more question am I doing this right or should I use router? Thank you.
// Include Express library
var express = require('express')
var app = express()
// Inlcude Request library
var request = require('request')
// Inlcude Http / Https library
var http = require('http')
var https = require('https')
app.use('/postman/tracks', function (req, res) {
res.setHeader('Content-Type', 'application/json');
var carrier = req.query.carrier
var number = req.query.number
var url = 'http://api.goshippo.com/v1/tracks/' + carrier + '/' + number
var response = request({
url: url,
json: true
}, function (err,res,obj) {
if (!err && res.statusCode === 200) {
console.log(JSON.stringify(obj))
//res.send(JSON.stringify(obj))
}
})
})
Using same variable name res
for the nested callbacks is the source of your problem , you should update your code to be
// Include Express library
var express = require('express')
var app = express()
// Inlcude Request library
var request = require('request')
// Inlcude Http / Https library
var http = require('http')
var https = require('https')
app.use('/postman/tracks', function (req, res) {
res.setHeader('Content-Type', 'application/json');
var carrier = req.query.carrier
var number = req.query.number
var url = 'http://api.goshippo.com/v1/tracks/' + carrier + '/' + number
var response = request({
url: url,
json: true
}, function (err, response ,obj) {
if (!err && response.statusCode === 200) {
console.log(JSON.stringify(obj))
res.json(obj);
}
})
})