gpt4 book ai didi

javascript - React 应用程序和 Laravel API 的 CORS 问题

转载 作者:行者123 更新时间:2023-11-30 11:04:39 24 4
gpt4 key购买 nike

我有一个位于 http://localhost:3000/ 的 React 应用程序Laravel API 位于 http://localhost/blog/public/api/
我收到以下错误

Access to fetch at 'http://localhost/blog/public/api/auth/signin' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Error Screenshot

这是响应 header :-

Response Headers Screenshot

我尝试通过 htaccess, https://packagist.org/packages/barryvdh/laravel-cors

最佳答案

以下解决方案应该可以解决 Laravel 中与 CORS 相关的问题。

第一步:创建一个新的中间件

‘Php artisan make:middleware cors’

第 2 步:

将下面放在创建的中间以替换句柄方法

    public function handle($request, Closure $next) {

return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');
}

第 3 步:

然后转到 Kernel.php 文件并将其添加到应用程序的全局 HTTP 中间件堆栈下。

附注只添加了最后一行注释,其他行之前已经存在。

protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\Cors::class,//cors added here
];

尽情享受吧!

关于javascript - React 应用程序和 Laravel API 的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56158474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com