如何修复Fetch API中的CORS问题 [英] How do I fix CORS issue in Fetch API

查看:62
本文介绍了如何修复Fetch API中的CORS问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 API I found and it gives the location as a JSON object. But when I request it through Fetch API, I'm getting this error.

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. 在Chrome中启用CORS可以解决错误,但是当我在heroku上部署应用程序时,如何通过移动设备访问它,而不会遇到同样的CORS问题。

  2. 我找到了一个代理API ,可以启用CORS请求。但由于这是位置请求,因此这为我提供了代理服务器的位置。所以这不是一个解决方案。

  3. 我已经完成了这个 Stackoverflow问题并在我的http请求中将标题添加到标题中,但它无法解决问题。 (仍然会出现同样的错误。)

  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 API which 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 question and added the headers to the header in my http request but it doesn't solve the problem. (Still it gives the same error).

那么如何永久解决问题呢?我可以用来解决Fetch API中http请求的CORS问题的最佳解决方案是什么?

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 ?

推荐答案

该API似乎是允许的,以回复 - 访问 - 控制 - 允许 - 来源:*

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

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

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

这在Firefox和Chrome中都适合我...

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

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

这篇关于如何修复Fetch API中的CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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