提取API无法加载,CORS

编程入门 行业动态 更新时间:2024-10-25 20:29:44
本文介绍了提取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

本文发布于:2023-11-24 19:47:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626576.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   API   CORS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!