CodeMed CodeMed - 5 months ago 35
JSON Question

Testing for and parsing JSON response in Node.js/Express.js

A Node.js server running Express.js handles an

HTTP GET
to
mydomain.com/myurl
by sending a
POST
to
http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl
. And the response comes back as simply JSON.

What code needs to be added to the routes.js file below in order to:

1.) create a separate handling block in the event that a request for mydomain.com/myurl is only JSON, and

2.) transfer the JSON response elements manually by name into variable1, variable2, variable3, etc.?


Here is
routes.js
, which handles the server-side routes:

var url = require('url');

module.exports = function(app) {

app.get('/myurl', function(req, res) {
app.post('http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl', function(req, res) {});
console.log('The POST is finished. Waiting for response.');
//need separate handler for JSON response that comes back from the other domain after this
});

app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the front-end)
});
};


The response from
POST http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl
might look like:

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
"var_one":"value1",
"var_two":"value2",
"var_three":1100
}

Answer

Your app.post call wont do a POST reqqest to another server, it is for setting up a POST route on your server. If you want to make HTTP requests to another server, it's esiest to use a library like request. Then you can use JSON.parse to turn the response JSON into a native JavaScript object.

Example:

var url = require('url');
var request = require('request');

module.exports = function(app) {

    app.get('/myurl', function(req, res) {
        request.post('http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl', function(err, response, body){
            if(err){
                //handle error here
            }
            var data = JSON.parse(body);
            var variable1 = data.var_one;
            var variable2 = data.var_two;
            var variable3 = data.var_three;
            //Do more processing here
        });
        console.log('The POST is finished.  Waiting for response.');
    });
};