reactjs - 从 React Azure 静态 Web 应用程序向 .NET Azure Function 发出请求时,为什么会收到 'blocked by CORS policy' 错误?

标签 reactjs .net azure cors apim

我正在开发一个Web应用程序,其前端为react(azure静态Web应用程序),后端为dotnet(部署为azure函数)。我遇到 CORS 错误:

从源“https://nice-sea-xxxxxxxx.3.azurestaticapps.net”访问“/limitMasterDetails/segmentLimit”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。

我尝试了以下步骤:

  • 修改函数应用 CORS 配置以允许来源
  • 修改 API 级别的 APIM Cors 政策以允许来源
  • 在 Startup.cs 类中添加 CORS 策略。
  • 修改函数应用 host.json 以允许来源
  • 清除了浏览器缓存并在不同的浏览器上尝试过。

这些步骤都没有帮助。请指教。

最佳答案

当 Web 应用程序尝试向不同的域、协议(protocol)或端口发出请求而服务器未明确允许时,就会出现您收到的错误,被 CORS 策略阻止

  • 检查您的 Azure Function CORS 设置。

enter image description here

  • 将 Azure Web 应用的来源添加到允许的来源。

enter image description here

  • 如果您使用自定义 header 或 HTTP 方法,请将它们添加到允许的 header 和允许的方法中。

  • 检查您是否已在 Azure Function 项目中安装 Microsoft.Azure.WebJobs.Extensions.Http NuGet 包及其依赖项。

检查 Azure 静态 Web 应用程序设置,确保您已在 React Azure 静态 Web 应用程序配置中正确放置了 Azure 函数的 URL 和终结点。

如果您在 Azure Function 之前使用 Azure API 管理,请检查 APIM 中的 CORS 设置并检查是否允许来源。 在Startup.cs文件中

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
            });
        });
    }
}

如果问题仍然存在,您需要检查是否还有其他CORS settings它们会覆盖您的函数应用设置。

有关更多信息,请参阅MS Doc1MS Doc2 .

关于reactjs - 从 React Azure 静态 Web 应用程序向 .NET Azure Function 发出请求时,为什么会收到 'blocked by CORS policy' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76395046/

相关文章:

reactjs - React.plotly.js 在数据点更改时重新绘制图形/组件

c# - 在 Entity Framework 中将对象添加到数据库时出现问题

azure - 304 : The condition specified using HTTP conditional header(s) is not met

c# - 无法将类型 'string' 转换为 'HtmlAgilityPack.HtmlDocument'?

sql - 重构 SQL 查询

python-3.x - 有没有办法在没有 Azure 的情况下通过 Power Automate 运行 python 脚本?

javascript - ReactJS 处理大量状态数据

javascript - 错误: Cannot read property 'props' of undefined,在子级中调用父级方法

reactjs - 返回上一个屏幕时执行 useQuery() Hook react 原生堆栈导航器

c# - 使用 DbContext 访问连接属性