访问节点请求的正文属性

Access body attributes of node request

本文关键字:正文 属性 请求 节点 访问      更新时间:2023-09-26

我正在向API发出HTTP GET请求,该API使用request包返回员工数据。API返回first_namelast_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)

MDN参考

尝试下面的代码段。

var request = require("request");
request({
  uri: "http://localhost:3000/api/employee",
  method: "GET"
}, function(error, response, body) {
  console.log( JSON.parse(body) );
});