CodeMed CodeMed - 1 year ago 124
JSON Question

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

A Node.js server running Express.js handles an

by sending a
. 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 is only JSON, and

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

Here is
, which handles the server-side routes:

var url = require('url');

module.exports = function(app) {

app.get('/myurl', function(req, res) {'http://some_other_domain_url_with_params?', 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?
might look like:

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


Answer Source

Your 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.


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

module.exports = function(app) {

    app.get('/myurl', function(req, res) {'http://some_other_domain_url_with_params?', function(err, response, body){
                //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.');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download