带有 ASP.NET 后端的 NGINX Docker 容器中的 Angular 收到 CORS 错误

问题描述 投票:0回答:1

我即将在 Docker 容器上分别部署我的前端(Angular 版本 16)和后端(ASP.NET Core 版本 7 和 dotnet 版本 7)。

这些容器位于我的 Raspberry Pi 4

([IP_ADDRESS]:4200 and [IP_ADDRESS]:5180)
上。 当我使用浏览器访问我的 Angular 应用程序时,我可以单击它,它似乎工作正常,直到我向后端发送请求。当我发送请求时,我得到:

“发布http://localhost:5180/api/auth/login net::ERR_CONNECTION_REFUSED”

URL 很好,因为两个 docker 容器都在同一台物理机器上,因此我想访问 localhost。

Chrome网络中的请求标头:

Accept:
application/json, text/plain, */*
Content-Type: application/json
Referer: [IP_ADDRESS]:4200/
Sec-Ch-Ua: [OMITTED] // I see the omitted values as not relevant
Sec-Ch-Ua-Mobile: [OMITTED]
Sec-Ch-Ua-Platform: "[OMITTED]"
User-Agent: [OMITTED]

没有响应标头。我的 Angular 日志记录显示: “http://localhost:5180/api/auth/login 的 HTTP 失败响应:0 未知错误”

这些是我的 Dockerfile:

角度

FROM node:18 as build

WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build 

FROM nginx:alpine
COPY --from=build /usr/src/app/dist/recipe_frontend /usr/share/nginx/html

EXPOSE 4200

CMD ["nginx", "-g", "daemon off;"]

ASP.NET

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /app
COPY . .
RUN dotnet restore
RUN dotnet build -c Release
RUN dotnet publish -c Release -o /app/publish
FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS final
WORKDIR /app
COPY --from=build /app/publish .
EXPOSE 5180
ENTRYPOINT ["dotnet", "recipe_backend.dll"]

我的 Docker 撰写文件:

version: '2.27.0'

services:
  frontend:
    build:
      context: ../dev/recipe-app/recipes/recipe_frontend
    ports:
      - "4200:80"
    depends_on:
      - backend
    networks:
        - recipe_network

  backend:
    build:
      context: ../dev/recipe-app/recipes/recipe_backend
    ports:
      - "5180:80"
    networks:
      - recipe_network

networks:
  recipe_network: 
    driver: bridge

我还使用 AllowAnyOrigin 激活了 CORS,这让我更加困惑,因为它不起作用。

我期待它能起作用,因为如果你问我的话,我的 Program.cs 文件已正确配置。 CORS 首先被激活,并在身份验证和授权之前使用。

程序.cs

using System.Text;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using recipe_backend.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors();
builder.Services.AddMvc();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// DB Connection
var versionNumber = builder.Configuration.GetSection("DB_Version").Get<int[]>();
var version = new MySqlServerVersion(new Version(versionNumber[0],versionNumber[1],versionNumber[2]));
var connectionStr = builder.Configuration.GetConnectionString("FullStackConnectionString");
builder.Services.AddDbContext<RecipesDbContext>(options => options.UseMySql(connectionStr, version));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});
builder.Services.AddAuthorization();
//builder.Services.AddRazorPages();

builder.Services.AddControllers().AddJsonOptions(options =>
{
// Omitted
});


builder.Services.AddHostedService<StartupService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    //app.UseSwagger();
    //app.UseSwaggerUI();
}

app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseHttpsRedirection();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

更令人困惑的是,这是我尝试调试的最重要的一点: 当我在本地 PC 上启动 Angular 应用程序并向我的 Raspberry Pi ASP.NET 后端 Docker 容器发送请求时,它完美运行!但我希望前端容器也能在 Raspberry pi 上工作...... 经过几个小时的配置 Program.cs 和检查请求后,我不知道该做什么了。

如何解决使用 Angular NGINX 容器时 CORS 策略失败的问题?

asp.net angular docker nginx cors
1个回答
0
投票

我发现错误: https://enable-cors.org/server_nginx.html

您必须在 NGINX 服务器上启用跨源资源共享(我在 docker 容器内使用它来运行我的 Angular 应用程序) 请参阅随附的链接。

© www.soinside.com 2019 - 2024. All rights reserved.