Home  >  Q&A  >  body text

Vue + Laravel Sanctum encounters 419 error with CSRF token mismatch

<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粉237029457P粉237029457420 days ago623

reply all(2)I'll reply

  • P粉073857911

    P粉0738579112023-08-25 16:18:42

    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! !

    reply
    0
  • P粉908643611

    P粉9086436112023-08-25 10:31:49

    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.

    reply
    0
  • Cancelreply