【问题标题】:Laravel + Vue.js (axios) using web route - UnauthenticatedLaravel + Vue.js (axios) 使用网络路由 - 未经身份验证
【发布时间】:2022-01-01 20:10:33
【问题描述】:

我有我的路由/web.php,如下所示:

Route::prefix('espace')->middleware(['auth'])->group(function () {
    Route::get('conversation/{id}', [MessageController::class, 'get_message'])->name('conversation.message');
    Route::post('searchUser', [UserController::class, 'search'])->name('user.search');
    Route::post('sendMessage', [MessageController::class, 'send_message'])->name('message.send');
    Route::post('getConversation', [MessageController::class, 'all_conversation'])->name('conversation.all');
});

我尝试使用 axios 在 vue js 上使用它们;

在我的刀片中,我有这个:

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

在我的 bootsrapt.js 中: let token = document.head.querySelector('meta[name="csrf-token"]');

window.axios = require('axios');
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');
}
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

我的 kernel.php:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

我已经收到了我的 csrf 令牌

,

用户已登录,但根据请求我收到错误 401“未验证”

【问题讨论】:

    标签: laravel routes middleware


    【解决方案1】:

    X-CSRF-TOKEN - 不是用于身份验证的令牌, 当您的路由使用 cookie 进行身份验证来保护“auth”中间件时

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 我该怎么办
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2020-08-26
    • 2017-01-28
    • 2023-03-10
    • 1970-01-01
    • 2019-06-14
    • 2017-02-14
    相关资源
    最近更新 更多