【问题标题】:TokenMismatchException using Laravel 5.1 and VueJSTokenMismatchException 使用 Laravel 5.1 和 VueJS
【发布时间】:2016-03-10 12:34:09
【问题描述】:

我正在尝试使用 VueJS 发出 POST 请求。但是,我无法通过 TokenMismatchException。 我在 Blade 主模板中有这个元标记:

<meta name="token" id="token" content="{!! csrf_token() !!}">

这在我的 VueJS 文件的顶部:

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');

这是我的 VueJS 方法中调用 POST 的行:

this.$http.post('ads/create/store', this.content);

我已经尝试了太长时间才能让令牌被接受。有人可以帮忙吗?

【问题讨论】:

  • 您是否检查了请求以确保标头设置正确?
  • 正在设置标题...但是,我认为不正确
  • 是否有 csrf 标记作为标头,您可能需要改用 getAttribute('content')
  • 我看到的唯一参考是 X-CSRF cookie

标签: laravel laravel-5.1 vue.js


【解决方案1】:

如果你在一个 vue 实例中:

vue = new Vue({

只需添加

Vue.http.headers.common['X-CSRF-TOKEN'] = '{{csrf_token()}}';    

$http 调用之前

this.$http.post('url(change here)', this.data)

【讨论】:

    【解决方案2】:

    将来可能更容易记住,您可以使用

    {{ csrf_field() }}
    

    如果您使用的是刀片模板引擎。

    【讨论】:

      【解决方案3】:

      你应该在meta标签和JSgetAttribute调用中使用'content'属性:

      html:

      <meta id="token" name="token" content="{{ csrf_token() }}">
      

      js:

      Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
      

      【讨论】:

      • 你的回答也是正确的......我选择了@RDelorier,因为他首先通过......不过,我确实支持你。 ——
      【解决方案4】:

      这是我的设置方法,希望对您有所帮助

      <meta name="_token" content="{{ csrf_token() }}">
      
      //get the token from the meta tag
      $('meta[name="_token"]').attr('content');
      

      【讨论】:

      • 谢谢!在 js 中使用“价值”而不是“内容”是我的错误,感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2016-02-15
      • 2017-01-20
      • 2016-10-31
      • 2016-06-29
      • 2016-03-03
      • 2015-09-05
      相关资源
      最近更新 更多