在Node.js / Express.js中测试和解析JSON响应

时间:2016-06-29 23:43:10

标签: javascript json node.js express

运行Express.js的Node.js服务器通过向HTTP GET发送mydomain.com/myurl来处理POSThttp://some_other_domain_url_with_params?reply_url=mydomain.com/myurl。响应简直就是JSON。

需要在下面的routes.js文件中添加哪些代码才能:
1.)如果对mydomain.com/myurl的请求仅为JSON,则创建单独的处理块 2.)按名称手动将JSON响应元素传输到variable1,variable2,variable3等?

这是routes.js,它处理服务器端路由:

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

POST http://some_other_domain_url_with_params?reply_url=mydomain.com/myurl的回复可能如下:

 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
 }

1 个答案:

答案 0 :(得分:2)

您的app.post电话不会对其他服务器执行POST请求,而是用于在服务器上设置POST路由。如果您想向其他服务器发出HTTP请求,最好使用像request这样的库。然后,您可以使用JSON.parse将响应JSON转换为本机JavaScript对象。

示例:

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