How do I fix CORS issue in Fetch API

2019-04-10 06:02发布

问题:

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. 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).

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 ?

回答1:

That API appears to be permissive, responding with 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.

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) )


回答2:

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:

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