CORS error even after setting Access-Control-Allow-Origin or other Access-Control-Allow-* headers on client side

Viewed 25257

I have a Vue application generated with webpack-simple option. I am trying to make a GET request to https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en but I get the error:

XMLHttpRequest cannot load https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access.

I am using vue-resource and have added:

Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'

That has no effect.

I also added this in the devServer option in the webpack.config.js:

devServer: {
  historyApiFallback: true,
  noInfo: true,
  headers: {
    "Access-Control-Allow-Origin": "*"
  }
}

That isn't solving the problem either; the error message remains the same.

How to go about solving this?

2 Answers

Ok, this answer is not really related to the question but it can be useful for those, who can't touch API server side, use free to use proxy service from Rob--W

function doCORSRequest(appUrl) {
  const cors_api_url = 'https://cors-anywhere.herokuapp.com/';
  let nUrl = cors_api_url + appUrl;

  fetch(nUrl)
    .then(response => {
      if(response.status !== 200) {
        alert("Error :( try later.")
        return;
      }
      response.json()
        .then(data => showResult(data))
    })
}

doCORSRequest(yourURL);
Related