0

I keep running into the error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I'm aware that this is a frequently asked question on the web, but i see no helpfull answer here on stackoverflow other than a workaround using JSONP.

My code is

  componentDidMount() {
    if (navigator.geolocation){
      function success(position) {
        var latitude  = position.coords.latitude;
        var longitude = position.coords.longitude;
        axios.get(`https://api.darksky.net/forecast/apikey/`+latitude+`,`+longitude+`?units=auto`)
        .then(result => {
          this.setState({
            daily: result.data.daily.data,
            loading: false,
            error: null
          });
        })
          .catch(err => {
            // Something went wrong. Save the error in state and re-render.
            this.setState({
              loading: false,
              error: err
            });
          });
      };
      function error() {
        console.log( 'geolocation error' )
      };
      navigator.geolocation.getCurrentPosition(success.bind(this), error);
    }
  }
frisk0
  • 259
  • 1
  • 6
  • 15
  • If none of the answers on the dupe target answer solve your problem, it might not be solveable. You must either follow the CORS policy, make the request without XHR (aka jsonp), or make the request from your server. – Kevin B Dec 01 '16 at 20:52

2 Answers2

0

If you are having access to server side application, follow the 1st answer provided by Mohamed Jahaber Sadiq

And if the purpose is just to see the results, you may use the "Allow-Control-Allow-Origin: *" chrome plugin which by defaults adds the header in all responses handled via chrome.

Arun
  • 49
  • 2
-1

It is a browser restriction for ajax calls, There are only three available options here.

  1. If you own the requested server you can add Access-Control-Allow-Origin as your application domain.

Else these two are the only options.

  1. Using JSONP as the response format n process using a callback.

  2. You can use server side proxy for eg. You can call yourapplication.com/somerequest in the nginx or apache config map 'somerequest' path to the external domain that you want to use i.e., api.darksky.net