Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I fix CORS issue in 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. 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 ?

like image 356
Thidasa Pankaja Avatar asked Feb 11 '18 04:02

Thidasa Pankaja


3 Answers

if you are making a post, put or patch request, you have to stringify your data with body: JSON.stringify(data)

fetch(URL, 
        {
            method: "POST", 
            body: JSON.stringify(data),
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
            }
        }
    ).then(response => response.json())
    .then(data => {
        ....
    })
    .catch((err) => {
        ....
        })
    });
like image 63
Nafiu Lawal Avatar answered Sep 21 '22 21:09

Nafiu Lawal


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) )
like image 36
Brent Bradburn Avatar answered Sep 22 '22 21:09

Brent Bradburn


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

like image 32
Tallboy Avatar answered Sep 18 '22 21:09

Tallboy