首页 > 解决方案 > Laravel 和 Vuejs 中的 CSRF 令牌不匹配

问题描述

我正在使用Axios将我的数据从 发布VueLaravel Controller

我已经使用下面的代码来解决问题。但它不工作!

import Axios from 'axios'
window.axios = require('axios');
Vue.prototype.$http = Axios;

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')
};

这是我要发布的方法:

onSubmit(event) {
  event.preventDefault();

  this.$http.post('store', {
     email: this.email
  }).then( (res) => {
     console.log(res.data.newsletter_success)
  }).catch( (err) => {
     console.log(err);
  })
}

问题是什么??CSRFLaravelbootstrap.js文件中有一个设置。

标签: laravelvue.jsaxios

解决方案


那么它可能是由您的代码中的前两行引起的:

import Axios from 'axios'
window.axios = require('axios');

您应该选择一种导入 axios 的方式并使用它

看看这个解决方案:

window.axios = require('axios');
Vue.prototype.$http = window.axios

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')
};

现在我们确定 Vue.prototype.$http(即 window.axios)也会发送您设置的 CSRF 标头。


推荐阅读