vue-resource icon indicating copy to clipboard operation
vue-resource copied to clipboard

Access-Control-Allow-Origin workaround

Open patrioticcow opened this issue 6 years ago • 5 comments

I an trying to to a simple get request, and I get an Access-Control-Allow-Origin error

Vue.http.get('https://some_url').then(response => {
      console.log(response);
}, response => {
      console.log(response);
});

If I do a regular xhr request, I don't get the error and all is good

  let createCORSRequest = function (method, url) {
      let xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest !== "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        xhr = null;
      }
      return xhr;
    };

    let xhr = createCORSRequest('GET', 'https://some_url');

    xhr.onload = function () {
      console.log(JSON.parse(this.responseText));
    };

    xhr.onerror = function () {};

If I try to do a jsonp request instead, I get Uncaught SyntaxError: Unexpected token :, basically failing to parse the json response.

Vue.http.get('https://some_url').then(response => {
      console.log(response);
}, response => {
      console.log(response);
});

Any ideas?

patrioticcow avatar May 16 '18 05:05 patrioticcow

Hi, if you want to set headers, i think you should do like that :

      this.$http.get('http://localhost:8080/api/v1/users',
      {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
            'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          }
        }
        ).then(function (response) {
          // Success
        }, function (response) {
          // Error
        })

msouidi309 avatar May 23 '18 13:05 msouidi309

Same error and work fine with XMLHttpRequest, last solution no work

thEpisode avatar May 30 '18 04:05 thEpisode

To fix this, you need to return some of the headers mentioned above from your server.

'Access-Control-Allow-Origin': '*'

MagnusPoppe avatar Dec 16 '18 15:12 MagnusPoppe

I cant change 'Access-Control-Allow-Origin': '*' as you suggested because I am using apis like github oauth. I am not building an API I am using it

smitpatelx avatar Mar 13 '19 09:03 smitpatelx

Enables cross-origin requests to anywhere via proxy.

let xhr = createCORSRequest('GET', 'https://cors-anywhere.herokuapp.com/https://some_url');

jwausle avatar Jul 20 '19 07:07 jwausle