pagekit / vue-resource

The HTTP client for Vue.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Access-Control-Allow-Origin workaround

patrioticcow opened this issue · 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?

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
        })

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

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

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

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

Enables cross-origin requests to anywhere via proxy.

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