我在尝试从我的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):
Postman请求: 当我使用Postman向API端点https://0748-102-146-2-29.ngrok-free.app/api/products-api发送GET请求时,我收到了预期的响应:
问题: 尽管我的Laravel API上有正确的CORS配置,但是可能是什么原因导致这个CORS问题?是否还有其他需要考虑的事项或任何额外的步骤,以确保我的React应用程序可以成功向API发出请求?非常感谢您提供任何见解或解决方案。谢谢!
“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发出请求?非常感谢您提供任何见解或解决方案。谢谢!