thunpisit
thunpisit

Reputation: 117

Request JSON data from URL and send respond out to document

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))
        }
    })
})

Upvotes: 0

Views: 452

Answers (2)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

The problem is that you're overriding express res with request res object.

app.use('/postman/tracks', function (req, res) {
    //...
    request({
        url: url,
        json: true
    }, function (err,response, obj) { //Changed res with response
        if (!err && response.statusCode === 200) {
            console.log(JSON.stringify(obj))
            //res.send(JSON.stringify(obj))
            res.json(obj)
        }
    })
})

Upvotes: 1

Ezzat
Ezzat

Reputation: 901

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);
        }
    })
})

Upvotes: 2

Related Questions