Vue + Laravel Sanctum encounters 419 error with CSRF token mismatch
P粉237029457
P粉237029457 2023-08-24 22:17:54
0
2
656
<p>I received a "419 (Unknown Status)" error with the error message "CSRF token mismatch."</p> <p>POST http://127.0.0.1:8000/login 419 (unknown status)</p> <p>CSRF token does not match.</p> <p>Laravel服务器:http://127.0.0.1:8000</p> <p>Vue服务器:http://localhost:8080</p> <p>应用程序/Http/Kernel.php</p> <pre class="lang-php prettyprint-override"><code>'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], </code></pre> <p>应用程序/模型/User.php</p> <pre class="lang-php prettyprint-override"><code><?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; //... } </code></pre> <p>配置/cors.php</p> <pre class="lang-php prettyprint-override"><code><?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, ]; </code></pre> <p>.env</p> <pre class="brush:php;toolbar:false;">SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080</pre> <p>src/main.js</p> <pre class="lang-js prettyprint-override"><code>axios.interceptors.request.use((config) => { config.baseURL = 'http://127.0.0.1:8000' config.withCredentials = true return config }) </code></pre> <p>src/views/auth/Login.vue</p> <pre class="lang-js prettyprint-override"><code>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 } } }; </code></pre></p>
P粉237029457
P粉237029457

reply all(2)
P粉073857911

I'm having trouble with this same issue. After several searches I found this page. After seeing possible suggested solutions, I modified

SANCTUM_STATEFUL_DOMAINS=localhost:8080

for

SANCTUM_STATEFUL_DOMAINS=http://localhost:8080

Then it will be fine! It works fine! !

P粉908643611

You set SANCTUM_STATEFUL_DOMAINS to localhost:8080, but the rest of the code shows you are using port 8000 instead of port 8080. If you change it to 8000 you should be fine.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template