TokenMismatchException using Laravel 5.1 and VueJS

2019-08-08 19:40发布

I am trying to use VueJS to make a POST request. But, I cannot get past a TokenMismatchException. I have this meta tag in the main Blade template:

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

And this at the top of my VueJS file:

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

Here is the line in my VueJS method that invokes the POST:

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

I have tried for way too long to get the token accepted. Can anyone out there help?

4条回答
三岁会撩人
2楼-- · 2019-08-08 19:51

You should use the 'content' attribute in the meta tag and JS getAttribute call:

html:

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

js:

Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('content');
查看更多
三岁会撩人
3楼-- · 2019-08-08 19:58

Here is how I set mine up, hope it helps

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

//get the token from the meta tag
$('meta[name="_token"]').attr('content');
查看更多
爷、活的狠高调
4楼-- · 2019-08-08 19:58

Possibly easier to remember for the future, you can use

{{ csrf_field() }}

If you are using the blade templating engine.

查看更多
我命由我不由天
5楼-- · 2019-08-08 20:08

If you are in a vue instance:

vue = new Vue({

Just add

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

before the $http call

this.$http.post('url(change here)', this.data)
查看更多
登录 后发表回答