首页 > 解决方案 > 部署到服务器时出现 CORS 问题

问题描述

我在同一台服务器上部署了两个项目。其中一个是 Angular 项目,另一个是 Angular 项目调用的.net CORE 中的 API。在本地我没有这个问题,但是在服务器上,每次我调用 API 时,我都会在浏览器控制台中收到以下错误消息:

访问 XMLHttpRequest 在 >' http://myIPAdress:81/Configuration/CODE_CLIENT ' 从源 >' http://myIPAdress ' 已被 CORS 策略阻止:不存在'Access-Control->Allow-Origin'标头请求的资源

我推断问题来自 .NET Core 项目。我已经在 StackoverFlow 上尝试过建议的解决方案,但没有成功。这是我在 .net Core 端的代码:

public void ConfigureServices(IServiceCollection services)
    {

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new 
CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
        });
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://localhost:80").AllowAnyHeader()
                .AllowAnyMethod());
        });

        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        loggerFactory.AddDebug(LogLevel.Information);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // Shows UseCors with named policy.
        app.UseCors("AllowSpecificOrigin");

        app.UseStaticFiles();
        app.UseAuthentication();


        app.UseMvcWithDefaultRoute();
    }

在 Angular 方面,我这样调用我的 API:

getConf(code : string){
    var url = "http://MyIPAdress/Configuration";
    return this.http.get<any>(url +'/'+ code)
}

在本地,我通过我的 API 访问数据,但不是在服务器上,有人知道为什么吗?

对不起我的英语和我的代码我开始编程

编辑:我在服务器的 IIS 中添加了一个 HTTP 响应:Access-Control-Allow-Origin。现在我没有同样的错误,但是这个:

响应中“Access-Control-Allow-Credentials”标头的值是 >'',当请求的凭据模式为“包含”时,该值必须为“真”。XMLHttpRequest 发起的请求的 >credentials 模式由 >withCredentials 属性控制。

标签: .netangularcorsasp.net-core-webapi

解决方案


builder => builder.WithOrigins("http://localhost:80").AllowAnyHeader(),同时http://localhost:80添加服务器 IP 地址

像这样:

builder.WithOrigins("http://localhost:80","http://serverIPAddress.com");

推荐阅读