访问节点请求的主体属性
Access body attributes of node request
我正在使用 request
包向 API returns 员工数据发出 HTTP GET 请求。 APIreturns等信息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)
试试下面的代码片段。
var request = require("request");
request({
uri: "http://localhost:3000/api/employee",
method: "GET"
}, function(error, response, body) {
console.log( JSON.parse(body) );
});
我正在使用 request
包向 API returns 员工数据发出 HTTP GET 请求。 APIreturns等信息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)
试试下面的代码片段。
var request = require("request");
request({
uri: "http://localhost:3000/api/employee",
method: "GET"
}, function(error, response, body) {
console.log( JSON.parse(body) );
});