Vue + Laravel sanctum CSRF token mismatch 419错误

Vue + Laravel sanctum CSRF token mismatch 419 error

我收到“419(未知状态)”错误消息“CSRF 令牌不匹配”。

POST http://127.0.0.1:8000/login 419 (unknown status)

CSRF token mismatch.

Laravel 服务器:http://127.0.0.1:8000

Vue 服务器:http://localhost:8080

app/Http/Kernel.php

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

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    //...
}

config/cors.php

<?php

return [
    'paths' => [
        'api/*',
        'sanctum/csrf-cookie',
        'register',
        'login',
    ],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];

.env

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080

src/main.js

axios.interceptors.request.use((config) => {
    config.baseURL = 'http://127.0.0.1:8000'
    config.withCredentials = true

    return config
})

src/views/auth/Login.vue

import axios from 'axios'
import { reactive } from '@vue/reactivity';

export default {
    setup() {

        const credential = reactive({
            email: '',
            password: '',
        })

        const login = async () => {
            axios.get('/sanctum/csrf-cookie').then( async () => {
                let response = await axios.post('/login', credential)
                console.log(response);
            });
        }

        return { login, credential }
    }
};

您将 SANCTUM_STATEFUL_DOMAINS 设置为 localhost:8080,但其余代码显示您 运行 在端口 8000 而不是 8080 上。如果将其更改为 8000,您应该是金色的。

我很难处理同样的问题。经过几次搜索,我登陆了这个页面。看到可能的建议解决方案后,我更改了

SANCTUM_STATEFUL_DOMAINS=localhost:8080

SANCTUM_STATEFUL_DOMAINS=http://localhost:8080

就是这样!效果很好!!