Access-Control-Allow-Origin is missing laravel-9 and vuejs3



我有一个vue3前端和一个laravel9后端。我想使用vue中的fetchapi将数据发送到后端并获得响应,但不幸的是,当我单击提交按钮时收到了此错误消息。有人知道我该怎么解决这个问题吗?

我试过水果蛋糕/laravel-cors库,但它仍然不起作用

firefox-de-toool]中的错误(https://i.stack.imgur.com/SCcqL.png)

<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

vuejs代码

methods: {
registerUser() {
fetch("http://localhost:8000/api/tippspiel/register", {
method: "POST",
body: JSON.stringify({
email: this.email,
username: this.username,
password: this.password,
passwordConfirmation: this.passwordConfirmation,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then((response) => {
return response.json();
}).then((data) => {
console.log(data);
})
}
}

控制器代码laravel

public function register(Request $request)
{
$data = $request->validate([
"email" => "required|email",
"username" => "required|min:6|max:15",
"password" => "required|min:12|max:40",
"passwordConfirmation" => "required|same:password",
"ageCheck" => "required|accepted",
"privacyCheck" => "required|accepted"
]);
return [
"status" => "ok",
"id" => 1,
"username" => $request->username
];
}

谢谢:(

创建名为Cors的新中间件,在其中放入以下代码:

public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => "*",
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin',
];
if ($request->getMethod() == "OPTIONS") {
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;
}

转到App\Http\Kernel.php,在protected $middleware数组中添加以下内容:

AppHttpMiddlewareCors::class,

protected $routeMiddleware阵列内,添加以下内容:

'cors' => AppHttpMiddlewareCors::class,

在您的路线文件中,添加以下内容:

Route::middleware(['cors'])->group(function(){
//your route here
});

在你的laravel文件夹中运行这个命令:

php artisan optimize:clear

最新更新