javascript 如何修复 Fetch API 中的 CORS 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48728173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:13:48  来源:igfitidea点击:

How do I fix CORS issue in Fetch API

javascriptreactjshttpcorsfetch-api

提问by Thidasa Pankaja

I'm building a front-end only basic Weather App using reactjs. For API requests I'm using Fetch API. In my app, I'm getting the current location from a simple APII found and it gives the location as a JSON object. But when I request it through Fetch API, I'm getting this error.

我正在使用 reactjs 构建一个仅限前端的基本天气应用程序。对于 API 请求,我使用的是 Fetch API。在我的应用程序中,我从我找到的一个简单 API 中获取当前位置,并将该位置作为 JSON 对象提供。但是当我通过 Fetch API 请求它时,我收到了这个错误。

Failed to load http://ip-api.com/json: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

So I searched through and found multiple solutions to fix this.

所以我搜索并找到了多种解决方案来解决这个问题。

  1. Enabling CORS in Chrome solves the error but when I deploy the app on heroku, how can I access it through a mobile device without running into the same CORS issue.
  2. I found an proxy APIwhich enables the CORS requests. But as this is a location request, this gives me the location of the proxy server. So it's not a solution.
  3. I've gone through this Stackoverflow questionand added the headers to the header in my http request but it doesn't solve the problem. (Still it gives the same error).
  1. 在 Chrome 中启用 CORS 解决了错误,但是当我在 heroku 上部署应用程序时,如何通过移动设备访问它而不会遇到相同的 CORS 问题。
  2. 我找到了一个启用 CORS 请求的代理 API。但由于这是一个位置请求,这给了我代理服务器的位置。所以这不是一个解决方案。
  3. 我已经完成了这个Stackoverflow 问题并将标头添加到我的 http 请求中的标头,但它没有解决问题。(仍然给出相同的错误)。

So how can I solve the issue permanently ? What's the best solution I can use to solve the CORS issue for http requests in Fetch API ?

那么我怎样才能永久解决这个问题呢?我可以用来解决 Fetch API 中 http 请求的 CORS 问题的最佳解决方案是什么?

采纳答案by nobar

That API appears to be permissive, responding with Access-Control-Allow-Origin:*

该 API 似乎是宽容的,响应 Access-Control-Allow-Origin:*

I haven't figured out what is causing your problem, but I don't think it is simply the fetch API.

我还没有弄清楚是什么导致了您的问题,但我认为这不仅仅是fetch API

This worked fine for me in both Firefox and Chrome...

这在 Firefox 和 Chrome 中对我来说都很好......

fetch('http://ip-api.com/json')
   .then( response => response.json() )
   .then( data => console.log(data) )

回答by Tallboy

You should use the proxy solution, but pass it the IP of the client instead of the proxy. Here is an example URL format for the API you specified, using the IP of WikiMedia:

您应该使用代理解决方案,但将客户端的 IP 传递给它而不是代理。以下是您指定的 API 的示例 URL 格式,使用 WikiMedia 的 IP:

http://ip-api.com/json/208.80.152.201

http://ip-api.com/json/208.80.152.201