如何修复 /sanctum/csrf-cookie 个错误
How to fix /sanctum/csrf-cookie errors
我正在使用 Laravel
Sanctum Axios API 创建 React js 项目。当我到达 sign-up 页面时,它显示以下错误。
cors.php
<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie','register', 'login' ],
'allowed_methods' => [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => [
'Origin',
'Content-Type',
'Accept',
'Authorization',
'X-Requested-With',
'X-CSRF-Token',
],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
现在显示以下错误
从来源 'http://localhost:3000' 访问 'http://localhost:8000/sanctum/csrf-cookie' 处的 XMLHttpRequest 已被 CORS 策略阻止:Access-Control-Allow-Headers 中的 Access-Control-Allow-Headers 不允许请求 header 字段 x-xsrf-token预检响应。
config/Session.php
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
];
.env 文件
APP_NAME="Crafty Shop"
APP_ENV=local
APP_KEY=base64:ECzTCbd8nfS6I82jRsd4sj4Bo6yJa0GRTfyTOrOoCno=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3310
DB_DATABASE=crafty
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
app.js
axios.defaults.baseURL= "http://localhost:8000/";
axios.defaults.headers.post['Content-Type'] ='application/json';
axios.defaults.headers.post['Accept'] ='application/json';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem('auth_token');
config.headers.Authorization = token ? 'Bearer ${}':'';
return config;
});
Login.js
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('api/login',data).then(res =>{
if(res.data.status === 200){
localStorage.setItem('auth_token', res.data.token);
localStorage.setItem('auth_name', res.data.username);
swal("Success", res.data.message,"success");
console.log(res.data.username);
history.push('/');
}
else if(res.data.status === 401){
swal("Warning", res.data.message,"warning");
}
else{
setLogin({...loginInput,error_list:res.data.validation_errors});
}
});
});
Sanctum.php
<?php
return [
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
'guard' => ['web'],
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'cors' => \App\Http\Middleware\CorsMiddleware::class,
],
];
您 MUST
在您的服务器应用程序上启用 CORS
。
了解 Laravel
是如何做到这一点的。
这个问题可能对你有帮助。
您需要授予对前端本地主机的访问权限才能将请求发送到后端 API。
因此,我建议您仔细按照 laravel 网站上的说明进行操作:
https://laravel.com/docs/8.x/sanctum#spa-configuration
如果您对某些步骤有任何疑问,可以问我。
但是我认为你的问题是你的前台URL不能发送请求,你必须允许它。但无论如何,首先你必须按照 link
中的步骤操作
我正在使用 Laravel
Sanctum Axios API 创建 React js 项目。当我到达 sign-up 页面时,它显示以下错误。
cors.php
<?php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie','register', 'login' ],
'allowed_methods' => [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => [
'Origin',
'Content-Type',
'Accept',
'Authorization',
'X-Requested-With',
'X-CSRF-Token',
],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
现在显示以下错误 从来源 'http://localhost:3000' 访问 'http://localhost:8000/sanctum/csrf-cookie' 处的 XMLHttpRequest 已被 CORS 策略阻止:Access-Control-Allow-Headers 中的 Access-Control-Allow-Headers 不允许请求 header 字段 x-xsrf-token预检响应。
config/Session.php
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
];
.env 文件
APP_NAME="Crafty Shop"
APP_ENV=local
APP_KEY=base64:ECzTCbd8nfS6I82jRsd4sj4Bo6yJa0GRTfyTOrOoCno=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3310
DB_DATABASE=crafty
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
app.js
axios.defaults.baseURL= "http://localhost:8000/";
axios.defaults.headers.post['Content-Type'] ='application/json';
axios.defaults.headers.post['Accept'] ='application/json';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem('auth_token');
config.headers.Authorization = token ? 'Bearer ${}':'';
return config;
});
Login.js
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('api/login',data).then(res =>{
if(res.data.status === 200){
localStorage.setItem('auth_token', res.data.token);
localStorage.setItem('auth_name', res.data.username);
swal("Success", res.data.message,"success");
console.log(res.data.username);
history.push('/');
}
else if(res.data.status === 401){
swal("Warning", res.data.message,"warning");
}
else{
setLogin({...loginInput,error_list:res.data.validation_errors});
}
});
});
Sanctum.php
<?php
return [
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
'guard' => ['web'],
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'cors' => \App\Http\Middleware\CorsMiddleware::class,
],
];
您 MUST
在您的服务器应用程序上启用 CORS
。
了解 Laravel
是如何做到这一点的。
这个问题可能对你有帮助。
您需要授予对前端本地主机的访问权限才能将请求发送到后端 API。
因此,我建议您仔细按照 laravel 网站上的说明进行操作: https://laravel.com/docs/8.x/sanctum#spa-configuration
如果您对某些步骤有任何疑问,可以问我。
但是我认为你的问题是你的前台URL不能发送请求,你必须允许它。但无论如何,首先你必须按照 link
中的步骤操作