Vue + Laravel Sanctum menghadapi ralat 419 dengan ketidakpadanan token CSRF
<p>Saya menerima ralat "419 (Status Tidak Diketahui)" dengan mesej ralat "Ketakpadanan token CSRF."</p>
<p>POST http://127.0.0.1:8000/login 419 (status tidak diketahui)</p>
<p>Token CSRF tidak sepadan.</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"><kod>'api' => [
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'pendikit:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
</code></pre>
<p>应用程序/模型/User.php</p>
<pre class="lang-php prettyprint-override"><code><?php
ruang nama AppModels;
gunakan IlluminateDatabaseEloquentFactoriesHasFactory;
gunakan IlluminateNotificationsNotifiable;
gunakan LaravelSanctumHasApiTokens;
class User extends Authenticatable
{
gunakan HasApiTokens, HasFactory, Notifiable;
//...
}
</code></pre>
<p>配置/cors.php</p>
<pre class="lang-php prettyprint-override"><code><?php
kembali [
'laluan' => [
'api/*',
'sanctum/csrf-cookie',
'daftar',
'log masuk',
],
'kaedah_yang dibenarkan' => ['*'],
'asal_asal_boleh' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'umur_maks' => 0,
'supports_credentials' => benar,
];
</code></pre>
<p>.env</p>
<pre class="brush:php;toolbar:false;">SESSION_DRIVER=kuki
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 = benar
kembalikan konfigurasi
})
</code></pre>
<p>src/views/auth/Login.vue</p>
<pre class="lang-js prettyprint-override"><kod>import axios daripada 'axios'
import { reaktif } daripada '@vue/reactivity';
eksport lalai {
persediaan() {
kelayakan const = reaktif({
e-mel: '',
kata laluan: '',
})
log masuk const = async () => {
axios.get('/sanctum/csrf-cookie').then( async () => {
biarkan respons = tunggu axios.post('/login', kelayakan)
console.log(respon);
});
}
return {log masuk, kelayakan }
}
};
</code></pre></p>