Fetch API 无法加载,cors

Fetch API cannot load, cors

在我的 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'
  }
})

但问题依然存在。

如何进行跨域请求?

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

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