简体   繁体   English

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

[英]Getting POST Request Message using React.JS

I am writing a program which has a "sign up" functionality. 我正在编写一个具有“注册”功能的程序。 The front-end is created using React.JS. 前端是使用React.JS创建的。 So far, I am able to using this code to send a post request in 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();
});

This works perfectly - for the user information is now in the database. 这非常有效-因为用户信息现在在数据库中。 However I am not sure how to get the response JSON using response.json(). 但是我不确定如何使用response.json()获取响应JSON。 I want to be able to take the response, get the message string, and display it to my user on the front-end. 我希望能够获得响应,获取消息字符串,并将其显示在前端的我的用户上。 This is the response when I run the same post request on Postman. 这是我在Postman上运行相同的发布请求时的响应。

{
    "message": "New user created"
}

Thanks for the help! 谢谢您的帮助!

response.json() returns a promise, so you need one more then to get the actual data: response.json()返回一个承诺,所以你需要一个更then获得实际的数据:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM