我正在使用节点包请求发送请求到我的后端。问题是,Request/GET和/ POST返回不同的实体。节点请求返回不同的结果
res.json()来自一个拥抱的express函数,所以不要混淆。
/GET返回JSON
request({
url: baseUrl + '/users',
method: 'GET'
}, function (error, response, body) {
if (error) {
res.send('500', 'Internal Server Error');
} else {
console.log(body);
res.json(response.statusCode, body);
}
});
的console.log(主体):
[{
"id": "1",
"forename": "John",
"surename": "Doe",
"birthdate": 1478953818343,
"email": "[email protected]"
}, {
"id": "2",
"forename": "John",
"surename": "Doe",
"birthdate": 1478953818343,
"email": "[email protected]"
}]
/POST返回JavaScript对象
request({
url: baseUrl + '/users',
method: 'POST',
json: {
email: req.body.email,
forename: req.body.forename,
surename: req.body.surename
}
}, function(error, response, body) {
if (error) {
res.send('500', 'Internal Server Error');
} else {
console.log(body);
res.json(response.statusCode, body);
}
});
的console.log(主体):
{ id: '3',
forename: 'John',
surename: 'Doe',
birthdate: 1478953818343,
email: '[email protected]' }
当我设置请求选项json:false时,两者都返回一个json。 当我设置请求选项json:true时,都返回javascript对象。
后端响应在两个请求上都是json。我不知道这种行为是一个错误还是我做错了什么。
请求文档说: json - 将body设置为值的JSON表示并添加Content-type:application/json头。此外,将响应正文解析为JSON。
body - body body用于PATCH,POST和PUT请求。必须是一个Buffer,String或ReadStream。如果json为true,则body必须是JSON序列化的对象。
那么,为什么/ GET返回JSON和/ POST返回javacript对象,当它在两个方法上接收json响应?
你能张贴在这里,对于'GET'和'POST'方法的反应,看看他们有什么不同? –
'当我设置请求选项json:true时,都返回javascript对象。是不是json选项的重点,..它基本上会自动为您的结果做一个JSON.parse。这是一个JavaScript对象,因为JSON只是一个字符串。 – Keith