POST获取请求 - 转换为JSON

时间:2017-12-04 12:24:41

标签: php reactjs post cors fetch

我试图从反应前端发送一个帖子请求到一个php文件。

handleFormSubmit(event) {
  event.preventDefault()
  let payload = this.state.email;
  fetch(`http://website.com/file.php`, {
    credentials: 'same-origin',
    method: 'POST',
    mode: 'cors',
    headers:{
      'Access-Control-Allow-Origin':'*'
      },
    body: payload
  })
  .then((response) => response.json() )
  .then((body) => {
    console.log(body);
    this.setState({
      email: body,
      message: 'Success!'
    });
  });
}

我收到错误消息而不是获取提取请求。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

1 个答案:

答案 0 :(得分:0)

看起来您的服务器不包含Access-Control-Allow-Origin标头以响应预检请求(OPTIONS)。如果缺少Access-Control-Allow-Origin,则CORS请求将失败。

以下是一些很好的文章,解释了CORS的工作原理:

https://www.html5rocks.com/en/tutorials/cors/

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

希望这有帮助!