gpt4 book ai didi

reactjs - Fetch API 无法加载,cors

转载 作者:行者123 更新时间:2023-12-03 13:38:25 25 4
gpt4 key购买 nike

在我的 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 ,除非您有充分的理由进行跨源请求。

关于reactjs - Fetch API 无法加载,cors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com