vendredi 30 décembre 2016

Call AJAX with Vue.js and Vue resource in Laravel

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

I have view:




<input @click="sendIt($event)" type="submit" value="Check prices" class="btn btn-success btn-theme" />


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="">

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire