如何使用 nodeJS 从 axios 库中获取有效的 JSON 响应
Posted
技术标签:
【中文标题】如何使用 nodeJS 从 axios 库中获取有效的 JSON 响应【英文标题】:How to get valid JSON response from axios library using nodeJS 【发布时间】:2020-12-16 16:33:19 【问题描述】:我正在尝试使用 AXios 库访问 REST 端点,并且 response.data 在 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 端点时,我可以得到整个响应 JSON,如下所示:
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,它返回的响应低于无法解析()
当我尝试使用 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);
);
【问题讨论】:
【参考方案1】:你确实得到了正确的数据,只是 node.js 没有在控制台/标准输出中显示它。您可以使用util.inspect()
获得更好的格式化输出。试试这个:
const util = require('util');
// ...
console.log(util.inspect(response.data, showHidden: false, depth: null ));
【讨论】:
是否可以将格式化的响应分配给任何变量?以上是关于如何使用 nodeJS 从 axios 库中获取有效的 JSON 响应的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 axios 从前端调用 uWebSockets http 路由?