dimanche 21 avril 2019

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 = ""
</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);
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire