Javascript ASP.NET核心API使Cors无法工作
第一次尝试使用asp.net core制作api时,我使用的是asp.net core 3.1。尝试发送GET请求时,我遇到此控制台错误:Javascript ASP.NET核心API使Cors无法工作,javascript,c#,asp.net-core,cors,Javascript,C#,Asp.net Core,Cors,第一次尝试使用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 pre
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();
});
}
public void配置服务(IServiceCollection服务)
{
services.AddCors(选项=>
{
options.AddPolicy(“AllowMyOrigin”,
builder=>builder.WithOrigins(
"http://localhost:8080/")
.WithMethods(“POST”、“GET”、“PUT”)
.带标题(“*”)
);
});
services.AddDbContext(opt=>
opt.UseSqlServer(Configuration.GetConnectionString(“数据库名”));
services.AddControllers();
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
//app.UseAuthentication();
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
附录UseCors(“AllowMyOrigin”);
//app.UseAuthorization();
//app.UseAuthentication();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
如果这是太少的信息,我会试图澄清,但就像我说的,这是我第一次做这样的事情,处理cors政策
建筑商。来源(“http://localhost:8080/))
请注意,指定的URL不能包含尾随斜杠(/
)。请修改下面的代码,然后检查它是否工作正常
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins(
"http://localhost:8080")
.WithMethods("POST", "GET", "PUT")
.AllowAnyHeader()
);
});
请尝试将此添加到内部
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
}