Laravel 11 cors 错误 - 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:

问题描述 投票:0回答:1

从源“https://laravel-react-survey-form.onrender.com”访问“https://laravel-react-survey-form-production.up.railway.app/api/signup”处的 XMLHttpRequest 具有被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

有人帮助我,当我尝试测试我部署的 Web 应用程序时,出现此错误。请注意,我使用 vite React js 作为我的前端,使用 php laravel 11 作为我的后端。

这是我的代码:

your text

	
reactjs laravel cors laravel-11 vite-reactjs
1个回答
0
投票

<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use App\Http\Middleware\CorsMiddleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__ . '/../routes/web.php', api: __DIR__ . '/../routes/api.php', commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->append(CorsMiddleware::class); }) ->withExceptions(function (Exceptions $exceptions) { // })->create(); <?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' => ['https://laravel-react-survey-form.onrender.com'], // Consider specifying your frontend URL here 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ]; <?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class CorsMiddleware { public function handle(Request $request, Closure $next): Response { $response = $next($request); return $response ->header('Access-Control-Allow-Origin', 'https://laravel-react-survey-form.onrender.com') ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Origin, X-Auth-Token, X-Requested-With'); } }

在此输入图片描述

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.