第一次嘗試使用 ASP.NET Core 制作 api,我使用的是 ASP.NET Core 3.1。當我嘗試發送 GET 請求時遇到此控制臺錯誤:Access to XMLHttpRequest at 'https://localhost:5001/api/items/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 我在這個網站和其他網站上嘗試了很多解決方案,但它們似乎對我不起作用。這是我的 Javascript 方面的內容:const sendRequest = async function(url) { try { let response = await axios.get(url); return response; } catch (error) { console.error(error); return []; }};這是我在 Startup.cs 中的內容public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowMyOrigin", builder => builder.WithOrigins( "http://localhost:8080/") .WithMethods("POST", "GET", "PUT") .WithHeaders("*") ); }); services.AddDbContext<DBContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DatabaseName"))); services.AddControllers(); }public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseCors("AllowMyOrigin"); //app.UseAuthorization(); //app.UseAuthentication(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }如果信息太少,我會盡力澄清,但就像我說的,這是我第一次做這樣的事情來處理 cors 政策。
ASP.NET Core API 啟用 Cors 不起作用
月關寶盒
2023-07-20 09:43:01