我正在向 API 发出 HTTP GET 请求,该 API 使用 request
包返回员工数据。 API 返回诸如 first_name
、last_name
等信息。
我的问题是如何从请求中访问这些属性?现在我有以下代码:
request("http://localhost:3000/api/employee", function(err, res, body) {
console.log(body);
});
这会将正文打印为字符串,而不是对象,因此我无法执行以下操作:
console.log(body.first_name) //returns 'undefined'
最佳答案
您必须使用 JSON.parse
解析该字符串才能成为 js 对象:
apiResponse = JSON.parse(body)
console.log(apiResponse.first_name)
关于javascript - 访问 Node 请求的body属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34486134/