我有 Asp .net core 3 web API。我正在使用 Fetch 調用其中一個 POST API,然后收到以下錯誤:Access to fetch at 'https://localhost:44395/api/challengeresponse/Verify' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Failed to load resource: net::ERR_FAILED因此,我研究并嘗試在 Web API 代碼中遵循以下內容:啟動.csprivate readonly string AllowedOriginPolicy = "_AllowedOriginPolicy";public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(AllowedOriginPolicy, builder => { var corsOrigins = new String[1] { "https://localhost:44395" }; builder.WithOrigins(corsOrigins).AllowCredentials().AllowAnyHeader().AllowAnyMethod(); }); }); services.AddControllers(); }public void Configure(IApplicationBuilder app, IWebHostEnvironment env){ app.UseCors(AllowedOriginPolicy); //at the end of the method.}盡管如此,我還是遇到了同樣的錯誤。我的 Fetch 代碼是:示例.jsasync function fetchdata(){ let _data = { OriginalData: "coordinateid", Signature: "URL", Certificate: "introduction" } const response = await fetch('https://localhost:44395/api/challengeresponse/Verify', { credentials: 'include', method: "POST", body: JSON.stringify(_data), headers: {"Content-type": "application/json; charset=UTF-8"}}).then(response => response.json()) .then(json => console.log(json)).catch(err => console.log(err));}這是一個非常常見的問題,但我仍然無法解決。請幫忙。編輯:請建議兩種類型的URL。因為我還在主服務器上部署了這個 Web API,所以從服務器 URL 訪問也會出現相同的錯誤。http://https://
CORS 策略已阻止從源“null”在“https://localhost:44395”處提取
牧羊人nacy
2024-01-18 09:50:37