Error making API requests using Axios and Vue-Resource

Asked

Viewed 273 times

1

It was consuming data from an API using XHR and was working very well, but there were some changes to the project and the need to use Vue arose. I tried to make the same requests using Axios and soon after Vue Resource but in both I was not successful.

Code using XHR:

var data = JSON.stringify(false);
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", "api/url");
xhr.send(data);
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === this.DONE) {
    console.log(this.responseText);
  }
});

Code using Axios:

axios({
  method: 'post',
  url: 'api/url',
  data: JSON.stringify(false),
  withCredentials: true
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Code using Vue-Resource:

  var data = JSON.stringify(false);
  this.$http.post("api/url", data, {
  headers: {
      credentials : true,
  }}).then(resp => console.log(resp));

Using both Axios and Vue-Resource I have the following error:

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

It seems a problem of CORS.

  • 1

    The message indicates yes. If Voce has access to the API, try releasing the CORS in it.

2 answers

1

By error, it is able to access the api but is blocked by Cors. You have to see this issue in the api, not on your site

0

You are experiencing CORS error, which is a security system that browsers use.

CORS - Cross-Origin Resource Sharing (Resource Sharing with different origins) is a mechanism that uses additional HTTP headers to inform a browser that allows a web application to be executed on a source (domain) with permission to access resources selected from a server at a different source. A web application executes a cross-origin HTTP request when requesting a resource that has a different origin (domain, protocol and port) from its own origin.

Official documentation may help you to better understand the error.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.