Can't make post with axios to Laravel App

2019-08-28 14:44发布

问题:

i tried many times to post an ajax request with axios using vuejs to lararvel app i added the csrf_token() in meta master blade. but the status always returns as 419 (Unknown Status), If some has got similar type of error then please help.

回答1:

You must assign value of csrf_token() to some field in your layout file. I would suggest you use like this:

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

If you are using Laravel mix to compile your JS & CSS, then the csrf_token is automatically added to the axios configuration. Following is the code in resources/assets/js/bootstrap.js for axios configuration whenever you create a Laravel application.

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
}

For above to work automatically, you need to run npm install or yarn install if you have installed yarn.