在本地 machine (mac-os) 的 Angular asp.net 核心应用程序上获取 CORS 问题

Getting CORS issue on Angular asp.net core app on local machine (mac-os)

从 Annular 应用程序调用 API 时出错:“Access-Control-Allow-Origin 不允许来源 https://localhost:44419。”。

问题

  1. 当 asp.net 应用程序和 angular 服务器 运行 都在源(本地主机)上时,为什么我 遇到跨源限制?
  2. 下面是我的 asp.net 代码和 angular proxy.conf 文件。我想我已经启用了所有设置,但仍然出现错误。

Angular 应用 运行 位于:http://localhost:44419 Asp.Net 应用 运行 位于:http://localhost:52703

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(
options=>options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.AllowAnyOrigin()
                          .AllowAnyMethod()
                          .AllowAnyHeader().SetIsOriginAllowed(origin => true);
                      })
);


app.UseCors();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

这是我的 angular proxy.conf.js 文件中的代码:

    const { env } = require('process');

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
  env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:52703';

const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
   ],
    target: target,
    secure: false,
    changeOrigin: true,
    headers: {
      Connection: 'Keep-Alive'
    }
  }
]

module.exports = PROXY_CONFIG;

我认为问题出在 proxy.conf.js 文件中。我在那里提到了 http url 和端口,而 asp.net 应用程序在 https 端口下是 运行。

因此,在我更正下面的 url 之后,问题似乎已经自行解决,我什至不需要上面列出的任何 app.useCors() 和相关设置(应用程序运行得很好,没有它,因为这里没有发生跨源访问,asp.net 和 angular app 运行 在同一台机器上)

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT} :

env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7067';