Roger Creasy
Roger Creasy

Reputation: 1529

TokenMismatchException using Laravel 5.1 and VueJS

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?

Upvotes: 1

Views: 2806

Answers (4)

Fabio de Oliveira
Fabio de Oliveira

Reputation: 11

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)

Upvotes: 0

Sean Whelan
Sean Whelan

Reputation: 319

Possibly easier to remember for the future, you can use

{{ csrf_field() }}

If you are using the blade templating engine.

Upvotes: 0

Douglas.Sesar
Douglas.Sesar

Reputation: 4430

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

Upvotes: 5

RDelorier
RDelorier

Reputation: 777

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

Upvotes: 2

Related Questions