2
votes

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:

axios.get(url, {
  headers: {
    'Authorization': 'Bearer TOKEN'
  }
})
.then(function (response) {
  console.log(response.data)
})

The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.

I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.

I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.

1
Have you tried "Access-Control-Allow-Origin: *" (single quotes around * removed) instead of "Access-Control-Allow-Origin: '*'"?yixiang
And you should also check if you have enabled "withCredentials", you can find this option in axios doc. This value allows Authorization header to be sent in cross site request, you should also ensure your web server send back "Access-Control-Allow-Credentials: true".yixiang

1 Answers

0
votes

I think you should add this code to the bootstrap.js (or where the axios is defined):

window.axios = require('axios'); // I think its already added

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest'
};

You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.