我有 Asp .net core 3 web API。我正在使用 Fetch 調(diào)用其中一個(gè) POST API,然后收到以下錯(cuò)誤: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 代碼中遵循以下內(nèi)容:?jiǎn)?dòng).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.}盡管如此,我還是遇到了同樣的錯(cuò)誤。我的 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));}這是一個(gè)非常常見的問(wèn)題,但我仍然無(wú)法解決。請(qǐng)幫忙。編輯:請(qǐng)建議兩種類型的URL。因?yàn)槲疫€在主服務(wù)器上部署了這個(gè) Web API,所以從服務(wù)器 URL 訪問(wèn)也會(huì)出現(xiàn)相同的錯(cuò)誤。http://https://
CORS 策略已阻止從源“null”在“https://localhost:44395”處提取
牧羊人nacy
2024-01-18 09:50:37