2016-11-13 82 views
0

我正在使用节点包请求发送请求到我的后端。问题是,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响应?

+0

你能张贴在这里,对于'GET'和'POST'方法的反应,看看他们有什么不同? –

+0

'当我设置请求选项json:true时,都返回javascript对象。是不是json选项的重点,..它基本上会自动为您的结果做一个JSON.parse。这是一个JavaScript对象,因为JSON只是一个字符串。 – Keith

回答

0

GET请求返回json字符串,因为您尚未将json选项设置为true。

在您的POST请求中,您希望发送一个正文,但是,这不是通过将对象传递给json来完成的。 json选项只是表示你的body应该被解码成json。 这就是为什么文档说:

如果json为true,那么body必须是JSON序列化的对象。

所以json仅仅是一个布尔值和body包含实际数据。

做身体POST请求的正确方法:

request({ 
    url: baseUrl + '/users', 
    method: 'POST', 
    json: true, // "sets body to JSON representation of value and adds Content-type: application/json header." 
    body: { 
      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 { 
      res.json(response.statusCode, body); 
    } 
}); 
+0

用console.log(body)输出编辑我的问题。 – mnlfischer

+0

那么,你的后端只是为每个请求方法提供不同的响应。所以也许你可以包含你的服务器端代码。 – schroffl

+0

我没有开发后端,只有bff。这是我的第二个想法,但是当我尝试邮递员发出相同的请求时,它会在两者上返回有效的json。 – mnlfischer