使用React.JS获取POST请求消息

时间:2018-02-20 02:42:13

标签: mongodb reactjs http-post fetch postman

我正在编写一个具有“注册”功能的程序。前端是使用React.JS创建的。到目前为止,我能够使用此代码在React.JS中发送帖子请求:

fetch('http://localhost:2000/users/signup/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "email": "testing@gmail.com",
        "password": "secret",
        "name": "matthew",
        "organization": "Apple"
      })
}).then(function(response) {
 return response.json();
});

这非常有效 - 因为用户信息现在位于数据库中。但是我不知道如何使用response.json()获取响应JSON。我希望能够获取响应,获取消息字符串,并将其显示给前端的用户。这是我在Postman上运行相同的帖子请求时的响应。

{
    "message": "New user created"
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

response.json()会返回一个承诺,因此您还需要一个then来获取实际数据:

.then(function(response) {
 return response.json();
})
.then(function(data) {
 console.log(data);
})

请参阅https://developer.mozilla.org/en-US/docs/Web/API/Body/json