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

时间:2019-05-15 22:30:21

标签: javascript php reactjs laravel cors

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

  

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

Error Screenshot

以下是响应标头:-

Response Headers Screenshot

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

5 个答案:

答案 0 :(得分:3)

创建新的中间件

‘Php artisan make:middleware cors’

将其放在创建的中间以替换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');
}

然后转到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 
 ];

享受!

答案 1 :(得分:0)

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

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

您可以使用它来解决此错误。

答案 2 :(得分:0)

您收到的错误是由于未在资源(您的Laravel API)上设置CORS策略标头造成的。
我知道您了解barryvdh's cors package,能否请您检查是否已遵循该软件包的安装过程?

更具体地说,在您的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' => ['*'],

答案 3 :(得分:0)

Laravel 7通过Barry的package

开箱即用地支持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,
];

答案 4 :(得分:0)

如果您使用的是CRA(create-react-app),则可以在react应用程序内部启用CORS。您需要在src文件夹中添加setupProxy.js文件。

const proxy =  require("http-proxy-middleware");
module.exports = (app) => {
  app.use(
    "/api/",
    proxy({
      target: "https://target.com/",
      changeOrigin: true,
      pathRewrite: {
        "^/api/": "/"
      },
    })
  );
};