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

后端 未结 2 609
有刺的猬
有刺的猬 2021-01-18 11:48

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: {
         


        
2条回答
  •  死守一世寂寞
    2021-01-18 12:26

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

提交回复
热议问题