【问题标题】:Fetch API cannot load, corsFetch API 无法加载,cors
【发布时间】:2017-07-25 09:55:50
【问题描述】:

在我的React 应用程序中,我试图从我的heroku 服务器发出GET 请求以获取用户列表:

https://blablabla.heroku.com/users

使用以下请求:

const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})

function loadMyUsers(data) {
  data.json().then((jsonData) => {
    // console.log(jsonData)

  })
}

sendSearch.then(loadMyUsers)}

但是我收到以下错误:

Fetch API cannot load https://blablabla.heroku.com/users.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' 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.

我尝试将我的 Fetch 方法更改为许多类似于:

const sendSearch = fetch('https://blablabla.heroku.com/users',{
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'mode': 'no-cors'
  }
})

但问题仍然存在。

如何进行跨域请求?

【问题讨论】:

  • 您必须在后端设置正确的Access-Control-Allow-Origin 标头。提取请求似乎有效。
  • 问题不在于您的前端,正如@Borma 在下面回答的那样,而在于您的服务器。您必须在服务器端启用 CORS

标签: reactjs get cors fetch


【解决方案1】:

在您的 Heroku 服务器上,您应该将 Access-Control-Allow-Origin: * 添加到您的响应标头中,或者如果您愿意,可以添加更具体的 Access-Control-Allow-Origin: http://localhost:8080

不过,在您的生产服务器上,您可能不需要此标头,除非您有充分的理由进行跨源请求。

【讨论】:

    猜你喜欢
    • 2019-11-20
    • 2022-11-04
    • 2020-03-21
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2017-04-29
    • 2018-01-11
    相关资源
    最近更新 更多