【问题标题】:Docker: Access to XMLHttpRequest has been blocked by CORS policyDocker:对 XMLHttpRequest 的访问已被 CORS 策略阻止
【发布时间】:2022-08-14 03:32:49
【问题描述】:

我在 Vsual Studio 2022 中创建了一个 ASP.NET Web 应用程序(.NET Framework)项目,并在其中创建了一个 Web 服务。 如果对 Web 服务的调用发生在 Locall IIS 中,则一切正常。当我将项目放入容器中时,没有任何效果。(Windows 容器)我做错了什么? 出现以下错误: 从源 \'http://172.17.78.68\' 访问位于 \'http://localhost:5002/WebService.asmx/HelloWorld\' 的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在 \'Access-Control-Allow-Origin\' 标头。 这是我的 docker-compose.yml:

version: \'3.4\'

services:

  saview:
    image: ${DOCKER_REGISTRY-}saview
    build:
      context: .\\SAview
      dockerfile: Dockerfile
    ports:
       - 5001:80
    links:
       - saviewweb
    depends_on:
       - \"saviewweb\"
    networks:
       - mynetwork

  saviewweb:
    image: ${DOCKER_REGISTRY-}saviewweb
    build:
      context: .\\SaviewWeb
      dockerfile: Dockerfile
    ports:
       - 5002:80
    networks:
       - mynetwork

networks:
     mynetwork: 
       driver: nat
       

这就是我使用 javascript 发出请求的方式:

function Web(arg, url ) {  
    var result;
    
    $.ajax(
        {
            type: \'POST\', url: url, data: JSON.stringify(arg),
            dataType: \'json\', 
            contentType: \"application/json; charset=utf-8\", async: false, success: function (res) {
                result = res;
            }
            , error: function (a1, a2, a3) {
                result =
                {
                    d: \"_Error_\" + a1 + \" \" + a2 + \" \" + a3
                };
            }  //-
        });
    if (result.d == null)
        return null;
    if (result.d.indexOf != undefined && result.d.indexOf(\"_Error_\") !== -1) {

        alert(result.d);
        return null;
    }
    return result;
}



Web({}, \"http://localhost:5002/WebService.asmx/HelloWorld\" );

    标签: javascript docker docker-compose


    【解决方案1】:

    当您尝试请求与运行 JavaScript 的域不同的域时,就会出现 CORS 问题。例如 http://localhost:3000http://example.com

    如果他们确实共享域,一切都会好起来的。

    请参考这些文档。一切都在那里https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

    正如文档中提到的那样,在 Program.cs 中添加一些东西应该可以解决问题:

    builder.Services.AddCors(options =>
    {
        options.AddPolicy(
            name: "cors-policy",
            policy  =>
                {
                    policy.WithOrigins(
                        "http://172.17.78.68:<port>",
                        "http://localhost:5002"
                    );
                }
        );
    });
    ...
    app.UseCors("cors-policy");
    

    WithOrigins 中,您希望指定允许请求 API 的所有“前端”。

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2020-05-05
      • 2020-03-12
      • 2019-04-28
      • 2021-10-27
      • 2019-09-23
      • 2020-05-30
      • 2021-10-05
      相关资源
      最近更新 更多