【发布时间】:2020-09-06 22:21:48
【问题描述】:
从 2 天以来,我一直在尝试使用 fetch 方法进行简单的 http 请求,但我无法摆脱 cors 错误。我将 http 标头放入 .htaccess 文件,但它似乎不起作用。
fetch('https://localhost:44326/api/Users', {
header: {
"Content-Type": "application/json"
},
method: 'POST',
body: JSON.stringify({ obj })
})
.then(response => console.log(response));
我一直得到有关 Access-Control-Allow-Origin 标头丢失的信息。有什么想法吗?
启动配置:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<ImageContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("ImageDB"));
});
services.AddCors(c => c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
【问题讨论】:
-
你能分享你的
startup类配置吗? -
记得在
app.UseRouting()后面加上app.UseCors("AllowOrigin");。
标签: reactjs entity-framework-core cors asp.net-core-webapi