【问题标题】:Laravel & Vue: trying to store data with axiosLaravel 和 Vue:尝试使用 axios 存储数据
【发布时间】:2019-12-17 04:50:34
【问题描述】:

用户流程是这样的:

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

我认为是 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 因为 API 不是无状态的
    • 但是如果我需要为网络存储数据,是否可以使用 api
    猜你喜欢
    • 2019-03-11
    • 1970-01-01
    • 2017-09-27
    • 2020-12-26
    • 2022-11-28
    • 2018-06-23
    • 2021-09-23
    • 2018-03-22
    • 2021-02-24
    相关资源
    最近更新 更多