Laravel 8 React Axios 的 CORS 问题

Laravel 8 CORS issue with React Axios

我将我的 API(使用 Laravel 8 框架构建)托管在子域中 - webapi.somedomain.com。我是 运行 本地版本的前端 UI 使用 React Framework 和 Axios 库构建的 HTTP 请求。我在共享主机中托管 space (cPanel + CentOS) 我在访问托管 API 时遇到问题。我已经陈述了我在下面看到的错误:

Access to XMLHttpRequest at 'http://webapi.somedomain.com/api/authorization/signup' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

所以我添加了 Laravel 自定义 CORS 中间件;使用 php artisan config:cache 更新了文件并清除了缓存。没有成功。 找不到任何其他资源。所以我添加了 Laravel CORS 包 - fruitcake/laravel-cors。已安装、发布并添加到中间件;更新了文件并清除了缓存。但是当从我的 React 项目中访问 API 时,我仍然看到 CORS 错误

config/cors.php:

    'paths' => ['api/*'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,

Kernel.php:

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

我只是 Laravel 的初学者。我究竟做错了什么?有人可以帮我吗?提前致谢。

P.S.: 我完全理解 CORS 是什么以及它是如何工作的。我是 Laravel 的新手。对开发并不陌生。我想知道我还应该做什么,以及我是否遗漏了什么。

问题是因为 .htaccess 文件。

在共享主机服务器中,重要的是只有项目的 public 文件夹可以在 public_html 文件夹中访问,其余的文件夹隐藏在私人文件夹中。

Link 你的 index.php 到私人的 autoload.php(public 不可访问的地方 - 根文件夹或 public_html 之外的任何文件夹)

将 Laravel 项目添加到共享主机工作区时,向 public_html 内 public 文件夹中的 .htaccess 文件添加一些规则很重要您的托管工作区的文件夹。

最终 .htaccess 文件应如下所示:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
       Options -MultiViews
   </IfModule>
   Options +FollowSymlinks
   RewriteEngine On

   # Redirect Trailing Slashes...
   RewriteRule ^(.*)/$ / [L,R=301]

   # Handle Front Controller...
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^ index.php [L]
</IfModule>

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

只有在这之后您才能运行 查询 Laravel 路线。如果不仅index.php会被执行,其他路由也不会被识别。

这可能是一个已知的。但由于我是初学者,我无法弄清楚这一点。将此添加为答案,以防其他初学者面临同样的问题。干杯。

如果您使用 apache2 为您的 laravel 应用程序提供服务,那么可能是 domain/subdomain 的 conf 文件存在问题,该文件为您的应用程序提供服务

要允许使用 .htaccess,您需要在块结束标记后将块添加到您的 conf 文件。类似于以下内容:


// File: /etc/apache2/sites-available/example.com.conf
// File: /etc/apache2/sites-available/example.com-le-ssl.conf

....
</VirtualHost>
<Directory /var/www/html/example.com/public_html>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

确保修改您的项目路径并确​​保在您的两个 conf 文件中包含此块,以防您的项目使用 SSL [https]

现在您的 .htaccess 文件中的任何配置都将被应用