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

2022-01-15 00:00:00 cors reactjs php javascript laravel

我有一个 React 应用程序,它位于

解决方案

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

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

‘Php artisan make:middleware cors’

第 2 步:

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

 公共函数句柄($request, Closure $next) {返回 $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 中间件堆栈下.

附言仅添加了带有注释的最后一行,其他行之前存在.

受保护的 $middleware = [IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,IlluminateFoundationHttpMiddlewareValidatePostSize::class,AppHttpMiddlewareTrimStrings::class,IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,AppHttpMiddlewareTrustProxies::class,AppHttpMiddlewareCors::class,//cors 添加在这里];

享受吧!

I have a React app which is at http://localhost:3000/ and Laravel API is at http://localhost/blog/public/api/
I get the following error

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.

Here are the response headers :-

I tried via htaccess, https://packagist.org/packages/barryvdh/laravel-cors

解决方案

The below solution should fix the CORS related issue in Laravel.

Step1: Create a new middleware

‘Php artisan make:middleware cors’

Step 2:

Put the below in the created middle to replace the handle method

    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');
}

Step 3:

Then go to Kernel.php file and add this under the The application's global HTTP middleware stack.

p.s. Only the last line with the comment was added, the other other lines exist before.

protected $middleware = [
IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
AppHttpMiddlewareTrustProxies::class,
AppHttpMiddlewareCors::class,//cors added here 
 ];

Enjoy!

相关文章