Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm making AJAX request in Laravel with Vue.js and Vue resource.

I have view:

{{Form::open(['method' => 'post', 'class' => 'form-inline', 'id' => 'main-form'])}}
{{Form::text('param1', null, ['id' => 'param1', 'class' => 'form-control'])}}
{{Form::text('param2', null, ['id' => 'param2', 'class' => 'form-control'])}}
<input @click="sendIt($event)" type="submit" value="Check prices" class="btn btn-success btn-theme" />
{{Form::close()}}

I have js:

var Vue = require('vue');
var VueResource = require('vue-resource');
Vue.use(VueResource);
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
const app = new Vue({
el: '#app',
methods: {
sendIt: function (e)
    {
        e.preventDefault();
        var token = $('[name="_token"]').val();
        this.$http.post('/data').then((response) => {
            console.log(response);
        }, (response) => {
            console.log(response);
        });
    }
}

Route:

Route::post('/data', 'MainController@data');

And controller:

public function data() 
{
    $msg = $this->test(); //method that retrieves data from db
    return response()->json(['msg'=> $msg], 200);
}

It gives me post 500 internal server error

In response I have this headers:

Cache-Control
Content-Type
Date
Phpdebugbar-Id
Server
Status
Transfer-Encoding
X-Powered-By

In network in my data site I have response headers without token, request headers with token and I have token in Request Payload.

If I change method to get I have same error but if I change method to get and if I remove from my controller part of code where I retrieve data from db and just pass string to json (example:

$msg = 'test';
return response()->json(['msg'=> $msg], 200);

I have success and I can output test on page.

So I'm not sure if it's some problem with token or something else. I tried and this:

var token = $('[name="_token"]').val();
this.$http.post('/prices', {_token:token})

but nothing. Same error again.

If I add this:

http: {
    headers: {
  X-CSRF-TOKEN: document.querySelector('#token').getAttribute('content')
    }
},

I have syntax error on page load.

If I change to this:

http: {
    headers: {
  Authorization: document.querySelector('#token').getAttribute('content')
    }
}

I got internal server error again.

And this is my token in main view:

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

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
    ]); ?>
</script>

EDIT:

This part works if I add quotes around x-csrf-token but still I have token mismatch error.

http: {
    headers: {
        'X-CSRF-TOKEN': document.querySelector('#token').getAttribute('content')
    }
},
share|improve this question
    
Have you checked your log file? (storage/logs/laravel.log). I would imagine there is already a fair amount in there so you might be better off deleting the file, and trying your request again, and then you should have more information on your error. Alternatively, if you go to the preview tab in your console then error should be in there as well. – Ross Wilson Dec 30 '16 at 23:24
    
I cleared log file but nothing new happens. But in preview I got TokenMismatchException in VerifyCsrfToken.php line 68: so it's about token. But I sent it :| – KondukterCRO Dec 30 '16 at 23:34
    
Do you know what version of Vue Resource you're using? – Ross Wilson Dec 31 '16 at 0:11
    
Vue version is 2.1.6 and resource is 1.0.3 – KondukterCRO Dec 31 '16 at 0:14

I could be mistaken but in your example at the top you have:

Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');

However, in your main view file you have:

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

You should be able to simply change $('meta[name=_token]') to $('meta[name=csrf-token]') (so they match).

Furthermore, the reason you had a syntax error with X-CSRF-TOKEN: ... is because you can't use hyphens in key names unless you wrap them in quotes i.e. 'X-CSRF-TOKEN': ....

Hope this helps!

share|improve this answer
    
I changed it but same errors again. Same headers are sent and same token mismatch error is shown. But now I don't have error on page load if I set http headers with x-csrf in quotes. – KondukterCRO Dec 31 '16 at 0:29
    
@KondukterCRO Are window.Laravel.csrfToken and the token in the request header the same? – PanJunjie潘俊杰 Jan 2 at 15:11
    
Yes they are same – KondukterCRO Jan 2 at 15:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.