简体   繁体   中英

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

Note: Please don't mark as duplicate as you can see from my code I have done exactly what the other answers say.

I have a web API for backend and a Node.js app for frontend.

Both of them are hosted on Microsoft Azure App Services.

Both of them have run fine locally, but recently I have deployed them to Azure and I am getting the following error when trying to call the API from the Node.js app:

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.

I have hidden the actual URL of the site but I can confirm it is identical to the one shown in the code below:

Here are the related parts of Startup.cs in the Web API:

...

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();
    });
}

Here is the endpoint that I am trying to access

[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)
    {
        ...
    }
}

I also think its important to mention that I can acces the enpoint locally even when not running the Node.js on port 3000, even though that's the only one that's listed in origins.

The issue was that even though CORS was enabled in the application code, there is also a CORS page in the Azure portal where a list of origins must be added.

To find it just Search for 'CORS' in the Azure portal search bar and add the URL of the site that you would like to have access to your endpoints.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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