![](/img/trans.png)
[英]CORS No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]"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.