use*_*977 5 get fetch cors reactjs
在我的React应用程序中,我试图GET从我的heroku服务器发出请求以获取用户列表:
https://blablabla.heroku.com/users
Run Code Online (Sandbox Code Playgroud)
使用以下请求:
const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})
function loadMyUsers(data) {
data.json().then((jsonData) => {
// console.log(jsonData)
})
}
sendSearch.then(loadMyUsers)}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
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.
Run Code Online (Sandbox Code Playgroud)
我尝试将我的Fetch方法更改为类似于以下内容的许多内容:
const sendSearch = fetch('https://blablabla.heroku.com/users',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'mode': 'no-cors'
}
})
Run Code Online (Sandbox Code Playgroud)
但问题仍然存在.
如何进行跨域请求?
小智 2
在您的 heroku 服务器上,您应该添加Access-Control-Allow-Origin: *响应标头,或者Access-Control-Allow-Origin: http://localhost:8080如果您愿意,可以添加更具体的标头。
但在您的生产服务器上,您可能不需要此标头,除非您有充分的理由进行跨源请求。
| 归档时间: |
|
| 查看次数: |
7632 次 |
| 最近记录: |