TheWebs TheWebs - 5 months ago 100
Ajax Question

Laravel (5.2) Token Mismatch on API Requests

So I have an interesting issue, as far as I know I am doing things correctly, how ever the token mismatch issue is coming up for API requests.

consider the following:

sendPostData() {
let params = {
title: this.state.post_title,
content: this.state.post_content,
tags: this.state.tags,
categories: this.state.categories,
blog_id: this.props.blogId,
};

$.ajax({
url: this.props.urlToPostTo,
type: 'POST',
header: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: params,
dataType: 'json'
}).done((data) => {
console.log(data);
});


}

When I
console.log($('meta[name="csrf-token"]').attr('content'))
I get a token string, so no issue there.

How ever when I post to the URL in question I get:

TokenMismatchException in VerifyCsrfToken.php line 67:


According to these docs I am doing things correctly ... I think.

Ideas?

Answer

You should send csrf-token value "headers" block instead of "header" block in ajax like below:

$.ajax({
    url: this.props.urlToPostTo,
    type: 'POST',
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    data: params,
    dataType: 'json'
}).done((data) => {
    console.log(data);
});