Я установил Sanctum и настроил конфигурацию Cors, как в каждом учебнике. но почему-то токен CSRF не может быть передан или что-то в этом роде, я не знаю. Он также не работает в Postman.
Laravel 11 AuthController:
Код: Выделить всё
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(['user' => $user, 'token' => $token], 201);
}
Код: Выделить всё
$middleware->append([
\Illuminate\Http\Middleware\HandleCors::class,
EnsureFrontendRequestsAreStateful::class, // Sanctum Middleware
AddQueuedCookiesToResponse::class, // Adds queued cookies to the response
StartSession::class, // Starts the session
ShareErrorsFromSession::class, // Shares session errors
VerifyCsrfToken::class, // Verifies CSRF tokens
]);
Код: Выделить всё
export const register = async (name: string, email: string, password: string, password_confirmation: string): Promise => {
// Step 1: Fetch CSRF token from Laravel
await useFetch('http://127.0.0.1:8000/api/sanctum/csrf-cookie', {
method: 'GET',
credentials: 'include', // Include credentials to get the CSRF cookie
});
// Step 2: Retrieve the XSRF-TOKEN from cookies
const token = useCookie('XSRF-TOKEN');
if (!token.value) {
throw new Error('CSRF token not found. Make sure cookies are enabled.');
}
// Step 3: Make the registration request
const { data, error } = await useFetch('http://127.0.0.1:8000/api/register', {
method: 'POST',
credentials: 'include', // Include cookies in the request
body: {
name,
email,
password,
password_confirmation
},
headers: {
'X-XSRF-TOKEN': token.value as string, // Set the CSRF token in the headers
},
});
// Handle any errors from the API
if (error.value) {
throw new Error(error.value.data.message || 'An error occurred during registration');
}
// Return token or some data as per your API response
// @ts-ignore
return data.value.token || 'Registration successful';
Подробнее здесь: https://stackoverflow.com/questions/790 ... csrf-error