【问题标题】:Getting POST Request Message using React.JS使用 React.JS 获取 POST 请求消息
【发布时间】:2018-02-20 10:47:48
【问题描述】:

我正在编写一个具有“注册”功能的程序。前端是使用 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 上运行相同的 post 请求时的响应。

{
    "message": "New user created"
}

感谢您的帮助!

【问题讨论】:

  • 你已经有了 json...它是response.json() 你应该可以通过控制台记录它...

标签: mongodb reactjs http-post fetch postman


【解决方案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

【讨论】:

  • 好的,你知道我如何在前端向用户显示这个响应吗?我会将此响应存储在变量中吗?
  • 通常你会使用setState({whatever: data})来存储值,然后通过this.state.whatever访问它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多