Riley
Riley

Reputation: 153

419 Error when attempting to post to my controller

I've been trying to submit a post request with axios to my projects controller and I keep getting an error 419(unknown status). Even though I'm passing the CSRF through headers to the controller. When I go into my network tab after posting it says:

X-CSRF-TOKEN: undefined
X-Requested-With: XMLHttpRequest

However, when I console.log(window.csrf_token) it returns a token.

This is included in my layout.blade.php

<script type="text/javascript">      
    window.csrf_token = "{{ csrf_token() }}"
</script>

I define the headers in my app.js for vue:

const axios = require('axios');

axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.csrf_token,
    'X-Requested-With': 'XMLHttpRequest',
};

and in my projects.vue here is my axios post request:

Swal.queue([{
title: 'Add a New Project?',
input: 'text',
inputAttributes: {
    autocapitalize: 'on'
},
showCancelButton: true,
confirmButtonText: 'Create Project',
showLoaderOnConfirm: true,
preConfirm: (result) => {
    return new Promise(function(resolve, reject) {
        if (result) {
            console.log(result)
            axios.post('/api/projects', {title:result})
            .then(function(response){
                Swal.insertQueueStep({
                type: 'success',
                title: 'Your project has been created!'
                })
                resolve();
            })
            .catch(function(error){
                Swal.insertQueueStep({
                type: 'error',
                title: 'Something went wrong.'
                })
                console.log(error);
                reject();
            })
        }
    });
}
}])

aswell as the store method in ProjectsController.php

    public function store()
    {
        $validated = request()->validate([
            'title' => 'required',
        ]);

        Project::create($validated);

        return response()->json($validated);
    }

Upvotes: 0

Views: 2347

Answers (1)

nakov
nakov

Reputation: 14248

Most probably you are setting the CSRF token in your layout file after the usage hence the reason of getting undefined.

Try using the default way, which is by putting a meta tag in your head of the main template like this:

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

Then to use it you may open the given bootstrap.js file where this code is already set:

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

Or if this does not exist, put it in your app.js script or whichever you use on every page.

Upvotes: 3

Related Questions