簡體   English   中英

Docker:對 XMLHttpRequest 的訪問已被 CORS 策略阻止

[英]Docker: Access to XMLHttpRequest has been blocked by CORS policy

我在 Vsual Studio 2022 中創建了一個 ASP.NET Web Application (.NET Framework) 項目,並在其中創建了一個 web 服務。 如果對 web 服務的調用發生在 Locall IIS 中,則一切正常。 當我將項目放入容器中時,沒有任何效果。(Windows 容器)我做錯了什么? 出現以下錯誤:從源“http://172.17.78.68”訪問“http://localhost:5002/WebService.asmx/HelloWorld”處的 XMLHttpRequest 已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header。 這是我的 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 正在運行的域不同的域時,CORS 就會出現問題。 例如http://localhost:3000http://example.com 並且固定在服務器/API 中,而不是前端。

如果他們確實共享域,一切都會好起來的。

請參考這些文檔。 一切都在那里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 的所有“前端”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM