提取API无法加载,CORS [英] Fetch API cannot load, cors

查看:45
本文介绍了提取API无法加载,CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my React app I am trying to make a GET request from my heroku server to get a list of users:

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方法更改为类似于以下内容的许多东西:

I tried changing my Fetch method to many things similar to:

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:* ,或更具体的访问控制允许来源:http://localhost:8080 (如果需要).

On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: http://localhost:8080 if you wish.

但是,在生产服务器上,除非有充分的理由要求跨源请求,否则可能不需要此标头.

On your production server though, you probably won't need this header, unless you have very good reason for cross origin requests.

这篇关于提取API无法加载,CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆