本文介绍了提取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:
blablabla.heroku/users使用以下请求:
const sendSearch = fetch('/blablabla.heroku/users', {credentials: 'same-origin'}) function loadMyUsers(data) { data.json().then((jsonData) => { // console.log(jsonData) }) } sendSearch.then(loadMyUsers)}但是我遇到以下错误:
Fetch API cannot load blablabla.heroku/users. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '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('blablabla.heroku/users',{ method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'mode': 'no-cors' } })但是问题仍然存在.
如何提出跨域请求?
推荐答案在您的Heroku服务器上,您应该在响应标头中添加 Access-Control-Allow-Origin:* ,或更具体的访问控制允许来源:localhost:8080 (如果需要).
On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: 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
发布评论