No 'Access-Control-Allow-Origin' header is present on the requested resource while calling a .NET web api from React app

huangapple go评论76阅读模式
英文:

No 'Access-Control-Allow-Origin' header is present on the requested resource while calling a .NET web api from React app

问题

我已经创建了一个 .Net Core 7 Web API,我正试图从一个React应用程序中调用它。我已经在我的后端代码中以以下方式添加了CORS策略 -

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    .WithOrigins("http://localhost:3000/")
    //.AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

然而,当我在React应用程序中记录响应时,我仍然收到以下错误消息 -

从来源 'http://localhost:3000' 到 'https://localhost:7063/api/CloneAPI' 的 fetch 访问已被 CORS 策略阻止:预检请求的响应未通过访问控制检查:请求的资源上未存在 'Access-Control-Allow-Origin' 标头。如果不透明的响应满足您的需求,请将请求的模式设置为 'no-cors' 以禁用 CORS 获取资源。

从来源 'http://localhost:3000' 到 'https://localhost:7063/api/CloneAPI' 的 fetch 访问已被 CORS 策略阻止:请求的资源上未存在 'Access-Control-Allow-Origin' 标头。如果不透明的响应满足您的需求,请将请求的模式设置为 'no-cors' 以禁用 CORS 获取资源。

如果我在后端代码中允许所有来源,如下所示 -

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    //.WithOrigins("http://localhost:3000/")
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

那么我能够成功获取所有数据。然而,出于安全原因,我不想允许所有来源。请问有人能帮我解决这个问题,为什么尽管设置了CORS并且URL也是正确的,我仍然收到此错误?

我的前端代码 -

const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://localhost:7063/api/CloneAPI")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setPosts(data);
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);
英文:

I have created a .Net Core 7 Web API and I'm trying to call it from a React app. I've added CORS policy in my backend code in the following manner -

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    .WithOrigins("http://localhost:3000/")
    //.AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

However, I'm still getting the following error in my React app when I log the response -

Access to fetch at 'https://localhost:7063/api/CloneAPI' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Access to fetch at 'https://localhost:7063/api/CloneAPI' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I allow all origins in my backend code like this -

builder.Services.AddCors(p => p.AddPolicy("corspolicy", builder =>
{
    builder
    //.WithOrigins("http://localhost:3000/")
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader();
}));

app.UseCors("corspolicy");

then I am able to fetch all the data successfully. However, I don't want to allow all origins due to safety reasons. Can someone please help me out on why I am getting this error despite setting up CORS and the URLs are correct too?

My frontend code -

  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch("https://localhost:7063/api/CloneAPI")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        setPosts(data);
      })
      .catch((err) => {
        console.log(err.message);
      });
  }, []);

答案1

得分: 1

请参考在ASP.NET Core中启用跨源请求(CORS)

> 注意:指定的URL不能包含尾部斜杠(/)。如果URL以/结尾,比较将返回false,不会返回标头。

只需在.WithOrigins()中删除尾部斜杠,配置如下:

.WithOrigins("http://localhost:3000")

然后,您可以正确访问您的端点,而无需CORS错误。

英文:

Refer to Enable Cross-Origin Requests (CORS) in ASP.NET Core
> Note: The specified URL must not contain a trailing slash (/). If the
> URL terminates with /, the comparison returns false and no header is
> returned.

Please remove the trailing slash in .WithOrigins(), just configure like:

.WithOrigins("http://localhost:3000")

then you can access your endpoint correctly without Cors error.

huangapple
  • 本文由 发表于 2023年6月4日 23:05:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定