How to set the X-XSRF-TOKEN or X-CSRF-TOKEN in the API Request Headers n Laravel and vue3

Viewed 49

How can I set the XSRF-TOKEN in Laravel 8 on bootstrap.js.

According to the file it is being handled automatically but when i try to access the user data it returns unauthorized.

My bosstrap.js codes

window._ = require('lodash');

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });
2 Answers

If you are using AJAX you can do this before any request:

    $.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
    },
    });

Assuming that you have a meta tag in your blade view:

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

If you are unable to get CSRF token from meta tag so you can prefix all routes under use vu by vu/ and exclude URIs from CSRF by simply adding them to the $except property of the VerifyCsrfToken middleware app/Http/Middleware/VerifyCsrfToken.php .

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'vu/*',
    ];
}

Documentation

Related