Laravel&Vue:尝试使用axios存储数据

时间:2019-08-09 12:32:48

标签: vue.js axios token csrf laravel-5.6

用户流程如下:

我正在尝试使用 / api / car / store 路径上的Axios将数据保存到laravel后端控制器中,但是在发出请求时收到401 HTTP错误。

>

我认为它是Header部分...

我假设我向axios.post发出请求时没有正确的标题数据。

VUE组件方法

saveCarDetails(){
    let config = {
        'Content-Type': 'application/json',
    }
    let currentObj = this;
    axios.post('/api/car/store', {
        user_id: currentObj.auth_user.id,
        car: currentObj.car
    }, config)
        .then(function (response) {
            console.log(response.data);
        })
        .catch(function (error) {
            currentObj = error;
        })
        .then(() => {
            this.errors.clear();
        })
}

Bootstrap.js

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;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

控制台错误 enter image description here enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为您需要在RouteServiceProvider中更改中间件以使用Web而不是api。