如何使用NodeJS从axios库获取有效的JSON响应
我正在尝试使用AXIOS库访问REST端点,并且response.data在console.log中返回以下内容:
I'm trying to hit the REST endpoint by using AXIOS library and the response.data return the below in console.log:
对console.log(response.data)的响应
{
sqlQuery: "select type,subtype from wetrade_p2 where parent_id='69341269'",
message: '1 rows selected',
row: [ { column: [Array] } ]
}
但是当我在邮递员中遇到相同的REST端点时,我可以像下面那样获得整个Response JSON:
But when I hit the same REST endpoint in postman and I can get the entire Response JSON as like below:
PostMan输出(预期):
{
"sqlQuery": "select type,subtype from wetrade_p2 where parent_id='69341269'",
"message": "2 rows selected",
"row": [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
}
我还尝试将response.data压缩,并返回到无法解析()的response之下
I also tried to stingify the response.data and it returned below response which is not able to parse()
当我尝试使用JSON.stringify(response.data)时,在console.log中获得以下响应:
sqlQuery: "select type,subtype from wetrade_p2 where parent_id=69341269"
message: "2 rows selected"
row: [
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "P",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
},
{
"column": [
{
"value": "W",
"name": "TYPE"
},
{
"value": "S",
"name": "STATUS"
},
{
"value": "0",
"name": "SUBTYPE"
},
{
"value": "USD",
"name": "CURRENCY"
}
]
}
]
示例代码:
await axios[methodType](url, body, {
httpsAgent:httpsAgent,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": true
}
}).then(response => {
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response.data);
console.log(JSON.stringify(response.data))
console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
console.log(response);
}).catch(error => {
console.log(error);
});
您确实获得了正确的数据,只是node.js不在控制台/stdout中显示它.您可以使用 util.inspect()
获得更好的格式化输出.试试这个:
You DO get the right data, just node.js doesn't display it in the console/stdout. You can use util.inspect()
for a better formatted output. Try this:
const util = require('util');
// ...
console.log(util.inspect(response.data, { showHidden: false, depth: null }));