繁体   English   中英

Azure 应用服务 API 中的“请求的资源上不存在‘访问控制允许来源’header”

[英]"No 'Access-Control-Allow-Origin' header is present on the requested resource" from Azure App Service API

注意:请不要像从我的代码中看到的那样标记为重复,我已经完全按照其他答案所说的那样做了。

我有一个用于后端的 web API 和一个用于前端的 Node.js 应用程序。

它们都托管在 Microsoft Azure 应用服务上。

它们都在本地运行良好,但最近我已将它们部署到 Azure 并且尝试从 Node.js 应用程序调用 API 时出现以下错误:

Access to XMLHttpRequest at '[API endpoint URL]' from origin '[https://....azurewebsites.net]'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

我隐藏了该站点的实际 URL 但我可以确认它与下面代码中显示的相同:

下面是Web API中Startup.cs的相关部分:

...

readonly string[] origins = { "http://localhost:3000", "https:/....azurewebsites.net" };

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddCors(options =>
    {
        options.AddDefaultPolicy(policy =>
        {
            policy.WithOrigins(origins)
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
        });
    });

    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseSerilogRequestLogging();
    app.UseRouting();
    app.UseCors();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

这是我要访问的端点

[Route("api/[controller]")]
[ApiController]
public class AuthController : BaseController
{
    ...
    [AllowAnonymous]
    [HttpGet]
    [Route("[action]")]
    [ProducesResponseType(typeof(string[]), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Organizations(string username)
    {
        ...
    }
}

我还认为值得一提的是,即使不在端口 3000 上运行 Node.js,我也可以在本地访问 enpoint,即使这是 origins 中列出的唯一一个。

问题是,即使在应用程序代码中启用了 CORS,Azure 门户中也有一个 CORS 页面,必须添加来源列表。

要找到它,只需在 Azure 门户搜索栏中搜索“CORS”,然后添加您希望访问端点的站点的 URL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM