CORS问题:Laravel 10 API请求中缺少'Access-Control-Allow-Origin'头部信息。

3
我在尝试从我的React应用程序向Laravel API发出GET请求时遇到了CORS(跨域资源共享)问题。控制台中显示的具体错误如下:
“Access to XMLHttpRequest at 'https://0748-102-146-2-29.ngrok-free.app/api/products-api' from origin 'http://localhost:19000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”
以下是我设置的相关细节: Laravel API配置(config/cors.php):
return [
'paths' => ['api/*', 'http://localhost:19000', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'], // Add other methods as needed
'allowed_origins' => ['*'],
'allowed_headers' => ['*'],
// ...
];

React应用程序(useProductFetch.js):

import { useState, useEffect } from "react";
import axios from "axios";

const fetchData = async () => {
setIsLoading(true);

try {
  const response = await axios.get(
    "https://0748-102-146-2-29.ngrok- 
    free.app/api/products-api"
  );
  console.log("Axios request successful");

export default useProductFetch;

Postman请求: 当我使用Postman向API端点https://0748-102-146-2-29.ngrok-free.app/api/products-api发送GET请求时,我收到了预期的响应:
{
"data": [
    // ...
]

}

问题: 尽管在Laravel API上配置了允许所有来源和方法的CORS,但我在从React应用程序发出请求时仍然面临CORS问题。我还验证过,当直接通过Postman访问时,服务器返回了预期的响应,就像这样"https://0748-102-146-2-29.ngrok-free.app/api/products-api"。
问题: 尽管我的Laravel API上有正确的CORS配置,但是可能是什么原因导致这个CORS问题?是否还有其他需要考虑的事项或任何额外的步骤,以确保我的React应用程序可以成功向API发出请求?非常感谢您提供任何见解或解决方案。谢谢!

请求在网络选项卡中返回200,但在响应头中缺少Access-Control-Allow-Origin。 - undefined
你解决了吗?我在使用React和Laravel 10时遇到了相同的问题。 - undefined
2个回答

0
我在自己的许多项目中也遇到了同样的问题。你需要创建一个中间件来解决这个问题。下面的代码是我一直在使用的中间件。我已经在其中添加了你的本地主机URL。
<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->headers->set('Access-Control-Allow-Origin' , 'http://localhost:19000');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
        return $response;
    }
}

在创建中间件之后,您必须在app/Http/Kernel.php文件的$routeMiddleware数组下定义中间件,例如:
protected $routeMiddleware = [
        ...(Any previous middlewares)       

        'cors' => \App\Http\Middleware\Cors::class,

    ];

一旦你完成了这个步骤,你就可以在API路由组或任何你创建的单独路由中使用它。例如:
Route::middleware(['cors'])->prefix('auth')->group(function () {
    Route::post('register', [AuthController::class, 'register']);
});

确保运行php artisan config:clear命令,以确保应用程序没有任何缓存的配置。

希望这能帮到你。


2
这不是正确的解决方案。自Laravel v9(截至2023年9月,当前版本为v10)起,已经内置了CORS。 - undefined
我承认,对于Laravel 10和9,必须有它们自己的正确处理方式。尽管我已经仔细阅读了文档,但我还没有找到解决方案,或许有一个变通方法可能会有所帮助。谢谢。 - undefined
我从未找到我问题的确切原因,但最终问题得到了解决。我建议在重新启动 artisan 开发服务器之前要特别小心,并清除所有缓存。 - undefined

-1
你可以安装Allow CORS: Access-Control-Allow-Origin Chrome扩展来解决这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接