pagekit / vue-resource

The HTTP client for Vue.js
MIT License
10.09k stars 1.6k forks source link

Access-Control-Allow-Origin workaround #692

Open patrioticcow opened 6 years ago

patrioticcow commented 6 years ago

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?

msouidi309 commented 6 years ago

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
        })
thEpisode commented 6 years ago

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

MagnusPoppe commented 5 years ago

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

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

smitpatelx commented 5 years ago

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

jwausle commented 5 years ago

Enables cross-origin requests to anywhere via proxy.

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