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

IT技术 javascript php reactjs laravel cors
2021-05-05 09:41:01

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

从源 ' http://localhost:3000 '获取在 ' http://localhost/blog/public/api/auth/signin '的访问已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头存在于请求的资源上。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

错误截图

这是响应标头:-

响应头截图

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

4个回答

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

Step1:创建一个新的中间件

‘Php artisan make:middleware cors’

第2步:

把下面的放在创建的中间替换handle方法

    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 中间件堆栈下。

ps 只添加了带有注释的最后一行,其他行之前存在。

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 
 ];

享受!

Laravel 7 通过 Barry 的支持开箱即用的 CORS

否则使用这个安装包 composer require fruitcake/laravel-cors

然后发布配置 php artisan vendor:publish --tag="cors"

然后根据需要修改它。

这是一个工作配置(小心,这允许来自其他来源的每个请求):

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS Options
    |--------------------------------------------------------------------------
    |
    | The allowed_methods and allowed_headers options are case-insensitive.
    |
    | You don't need to provide both allowed_origins and allowed_origins_patterns.
    | If one of the strings passed matches, it is considered a valid origin.
    |
    | If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
    | all methods / origins / headers are allowed.
    |
    */

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => true,
];

在 Laravel 中访问 API 时不会出现 CORS 错误,那么您需要在 Laravel 项目中添加 CORS PKG。

https://github.com/barryvdh/laravel-cors

您可以使用它来修复此错误。

您收到的错误是由于未在您的资源(您的 Laravel API)上设置 CORS 策略标头。
我看到你知道barryvdh 的 cors 包,你能检查一下你是否遵循了该包的安装过程吗?

更具体地说,在您的Http/Kernel.php文件中包含以下内容

protected $middleware = [
    // ...
    \Barryvdh\Cors\HandleCors::class,
];

或者

protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

第一个将中间件全局注入到您的应用程序中,第二个将它注入到 api 守卫中,如果您已经在routes/api.php其中定义了 api 路由,那么它也应该可以正常工作。


此外,您可以尝试发布包的配置php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"并将允许的标头更改为'allowedHeaders' => ['*'],