Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios - No 'Access-Control-Allow-Origin' header is present

Tags:

cors

axios

I'm missing something here. I was struggling to get the API call to work. Then I split the url up like below and it works -literally once. After that it fails to work again. I swear I did not change something.

How do you go about it in AXIOS?

Error message is:

XMLHttpRequest cannot load http://magicseaweed.com/api/W2Z26fXscpELi7nPB0svfqcGj9FtGO9e/forecast/?spot_id=228. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

import axios from 'axios';

const ROOT_URL = `magicseaweed.com/api/W2Z26fXscpELi7nPB0svfqcGj9FtGO9e/forecast/`;

export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather() {
    const url = `http://${ROOT_URL}?spot_id=228`;
    const request = axios.get(url);

    return {
        type: FETCH_WEATHER,
        payload: request
    };
}

I tried with this modified GET aswell, but to no avail

axios({
  url: url ,
  headers: {"Access-Control-Allow-Origin": "*"},
});
like image 243
morne Avatar asked Oct 12 '16 20:10

morne


1 Answers

Look here:

https://www.npmjs.com/package/magicseaweed

Towards the bottom it says why their API wrapper won't work in the browser. It's the same reason you can't make the Ajax call in the browser.

FAQ

Can I use this module in the browser with browserify?

In theory yes, but the Magicseaweed API is currently not sending the Access-Control-Allow-Origin header in browser requests (somehow the header is sent if you replay the request via cURL).

So if the API changes that behavior, this module will work with browserify.

You can stand up your own proxy server or you can use one of the free ones available on the internet:

https://developer.yahoo.com/yql/

https://crossorigin.me/

like image 152
Robert Moskal Avatar answered Sep 29 '22 10:09

Robert Moskal