Home » vue » Laravel & Vue: trying to store data with axios

Laravel & Vue: trying to store data with axios

Posted by: admin November 26, 2021 Leave a comment

Questions:

The userflow is like this:

I’m trying to save data into a laravel backend controller with Axios on the route /api/car/store, but I’m recieving a 401 HTTP error when emitting the request.

I think its the Header part…

I assume I do not have the right header data when I make a request with axios.post.

VUE component method

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');
}

Console error
enter image description here
enter image description here

enter image description here

Answers:

I think you need to change your middleware in RouteServiceProvider to use web instead of api.