【问题标题】:CSRF token mismatch in Laravel and VuejsLaravel 和 Vuejs 中的 CSRF 令牌不匹配
【发布时间】:2021-04-14 23:36:21
【问题描述】:

我正在使用Axios 将我的数据从Vue 发布到Laravel 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);
  })
}

有什么问题?? Laravel bootstrap.js 文件中有一个 CSRF 设置。

【问题讨论】:

    标签: laravel vue.js axios


    【解决方案1】:

    这可能是由您的代码中的前 2 行引起的:

    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 标头。

    【讨论】:

      【解决方案2】:

      你可以给headers点赞ajaxSetup

      this.$http.post('store', { email: this.email}, 
      { 
         headers: {
           'Content-Type': 'application/json', 
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
         } 
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-08
        • 2016-12-10
        • 2016-09-20
        • 2020-01-20
        • 2020-06-17
        • 1970-01-01
        • 2020-07-18
        • 2020-05-02
        • 2016-10-15
        相关资源
        最近更新 更多