在 Express.js 中解析 JSON 响应正文

Parsing JSON response body in Express.js

本文关键字:JSON 响应 正文 Express js      更新时间:2023-09-26

A Node.js/Express.js 应用程序对另一个应用程序进行 RESTful 调用并接收 JSON 作为响应。 但是 JSON 响应不会解析为新变量。 需要对下面的代码进行哪些具体更改,以便 JSON 正文可以成功解析为接收 Node.js/Express.js 应用可用于进一步处理的新变量?

以下是当前正在接收JSON body response的 Node.js/Express.js 代码:

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

下面是代码中显示的GETnodemon日志。 请注意,从不调用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

这是格式化和截断的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"
}

问题是你表现得好像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);

以下行不会等待您的响应被解析。

res.send(body);

将其删除并等待从response.on('end')事件中响应。


编辑以包含重组请求

我会以不同的方式构建您的请求。您没有流式传输响应,因此没有太多理由侦听响应事件。此外,您还可以通过指示返回的正文为 JSON 来让请求为您处理JSON.parse(),从而摆脱对的需求。

request({
    method: 'GET',
    url: authServer + '/uaa/user', 
    json: true, // indicates the returning data is JSON, no need for JSON.parse()
    auth: {
        user: null,
        password: null,
        sendImmediately: true,
        bearer: bearerToken 
    }
}, function (error, response, body) {
    if(error){
      console.log('ERROR with user request.');
      return res.sendStatus(500);  // Return back that an error occurred
    }
    else {
        console.log(response.statusCode); 
        console.log(body);
        var text = '';
        for (var key in body) {
            text += 'Index is: ' + key + ''nDescription is:  ' + body[key];
        }
        return res.status(200).send(text);       
     }  
});