Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers

I'm making a get request to embed.rock using vue and axios.

axios({
  method: 'get',
  url: 'https://api.embed.rocks/api?url=' + this.url,
  headers: {
      'x-api-key': 'my-key'
  }
})

When I use a CDN to get vue and axios with an inline script my code works fine and I get a response back.

When I reference the installed vue and axios scrpts with an external script the code no longer runs and I get the following error:

Failed to load https://api.embed.rocks/api?url=https://www.youtube.com/watch?v=DJ6PD_jBtU0&t=4s: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.

When I click on the error in the console it just brings me to:

<!DOCTYPE html>
like image 223
user3325126 Avatar asked Jul 05 '18 20:07

user3325126


2 Answers

Laravel is setting a global configuration to include automatically the X-CSRF-TOKEN in the headers of the request in your bootstrap.js file.

let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Therefore, if you want to remove the token, you can achieve it like this:

var instance = axios.create();
delete instance.defaults.headers.common['X-CSRF-TOKEN'];

instance({
    method: 'get',
    url: 'https://api.embed.rocks/api?url=' + this.url,
    headers: {
        'x-api-key': 'my-key'
    }
});
like image 122
Chin Leung Avatar answered Nov 10 '22 10:11

Chin Leung


the problem is that by default the CSRF Token is register as a common header with Axios so to solve this issue :

1- replace these lines in bootstrap.js

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf- 
token');
}

by this line

window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

2- install qs module by npm ..... using thie link : https://www.npmjs.com/package/qs

3- define const of qs like below : const qs = require('qs');

4- use axios by defult like this :

axios.post('your link here ',qs.stringify({
  'a1': 'b1',
  'a2 ':'b2'
}))
.then(response => {alert('ok');})
.catch(error => alert(error));
like image 22
Taif Raoof Avatar answered Nov 10 '22 09:11

Taif Raoof