0
votes

I want to send a request to Laravel from Vue to update a column for the currently logged in User.

So far I have setup Vuex, where I am sending a a post request with axios. however I keep getting an error 419. which apparently means its a CSRF token problem.

  1. How would I parse the CSRF token to my backend the current method in my code does not work.

  2. is there a alternative route that would be easier.

Route in api.php

Route::group(['middleware' => 'web'], function () {
    Route::post('prequalify', 'OfferController@update');
});

controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;

class OfferController extends Controller
{
    function update(Request $request){
        $user = Auth::user();
        return $user;
        //Send Request to Majestic and get a response
        $response = true;
            if($response){
                $user->is_qualified = true;
            }else{
                $user->is_qualified = false;
            }

            $user->save();


        return $request;
    }
}

Vue Method and I am able to get the CSRF token.

preQualify(){
        let csrf= document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        this.$store.dispatch('prequalify',{csrf});
    }

VUEX actions

import axios from 'axios';
let actions = {
    prequalify({commit,state}, payload){
        axios.defaults.headers.common['X-CSRF-TOKEN'] = payload.csrf;
        axios.post('/api/prequalify',state.LoanCalculator)
            .then(res => {
                console.log(res);
            })
    }
}
export default actions

2

2 Answers

1
votes

In your api.php you are using web middleware which checks for VerifyCsrfToken middleware that middleware responsibility to verify CSRF tokens and that what gives you the 419, to make it simpler you need to remove web middleware

Route::group(['middleware' => []], function () {
    Route::post('prequalify', 'OfferController@update');
});

in this case there is no need for sending X-CSRF-TOKEN in your axios call.

Note - if prequalify endpoint requires that user should be authenticated you need to use the right middleware corresponding to auth system you are using which could passport or sanctum.

0
votes

i used like this

in bootstrap.js

window.csrfToken = $('meta[name="csrf-token"]').attr("content");

then in axios req.

 axios.post('/api/prequalify',{_token:csrfToken,data:state.LoanCalculator})
            .then(res => {
                console.log(res);
            })

may be there is any better way but i used this in my application hope it can solve your issue