在Express.js中解析JSON响应主体

Dol*_*fee -2 javascript json node.js express

Node.js/Express.js应用程序对另一个应用程序进行RESTful调用,并在响应中接收JSON.但是JSON响应没有被解析为新变量. 需要什么具体改变如下的代码来进行,使人体JSON可以成功地解析到新的变量,该接收的Node.js/Express.js应用程序可用于进一步的处理?

这是Node.js/Express.js代码,它当前正在接收JSON body response:

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

app.get('/user**', function(req, res) {
    console.log("You Hit The User Route TOP");
    request.get(authServer + '/uaa/user', function (error, response, body) {
        if(error){console.log('ERROR with user request.')}
        if (!error){// && response.statusCode == 200) {
            console.log(response.statusCode); console.log(body);

             response.on('data', function(chunk){
                 console.log('inside response.on(data...)');
                 body += chunk;
             });

             response.on('end', function(){
                 console.log('inside response.on(end...)');
                 body = JSON.parse(body);
                 var text = '';
                 for (var key in body){
                      text += 'Index is: ' + key + 
                              '\nDescription is:  ' + body[key] 
                 }

                 // The Description is:  "descriptive string"  
                 console.log("Got a response: ", text);
                 res.send(text);            
             });
            res.send(body);
        };
    }).auth(null, null, true, bearerToken);//this inserts bearer token in the GET request
    console.log("You Hit The User Route BOTTOM");
});
Run Code Online (Sandbox Code Playgroud)

以下是代码中显示的nodemon日志GET. 请注意,response.on()永远不会调用块,因为它们的SYSO永远不会打印:

You Hit The User Route TOP
You Hit The User Route BOTTOM
200
{ long JSON string, which is formatted and truncated below for easier reading }
GET /user 200 182.862 ms - 1296
Run Code Online (Sandbox Code Playgroud)

这里是格式化和截断的JSON body,它说明了需要解析成Node.js/Express.js JavaScript变量的数据格式:

{
    "details":  
        {
            "remoteAddress":"127.0.0.1",
            "sessionId":null,
            "tokenValue":"SomeLongTokenString",
            "tokenType":"Bearer",
            "decodedDetails":null
        },
    "authenticated":true,
    "userAuthentication":
        {
            "details":null,
            "authorities":
                [
                    {
                        "authority":"ROLE_ADMIN"
                    },
                    {
                        "authority":"ROLE_USER"
                    }
                ],
            "authenticated":true,
            "principal":"user",
            "credentials":"N/A",
            "name":"user"
        },
    "name":"user"
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*uck 5

问题是你的行为好像response是一个逐渐给你JSON的流,但是你已经向自己证明了你的第一个console.log(body)声明是不正确的.相反,您可以body立即解析并开始处理它.您还可以简化请求处理程序.

if (error) {
  console.log('ERROR with user request.')
  return res.sendStatus(500);
}

body = JSON.parse(body);
var text = '';
for (var key in body) {
  text += 'Index is: ' + key + '\nDescription is:  ' + body[key]
}
// The Description is:  "descriptive string"  
console.log("Got a response: ", text);
res.send(text);
Run Code Online (Sandbox Code Playgroud)