【发布时间】:2021-03-13 08:34:08
【问题描述】:
我目前正在关注一个 React 教程,其中有一次使用 axios 从一个虚假的 web 服务中获取数据。 我决定使用 Visual Studio 社区 2019 中的 ASP.net Core 应用程序 A{I 模板制作一个简单的 Web 服务器,添加一个新控制器以返回一些硬编码数据。
服务器一切正常,当我使用邮递员点击它时,我可以使用序列化的 json 对象从我的 get 方法中检索一个字符串。
然后我尝试让 axios 运行相同的 get 请求,并且我不断收到
从源“http://localhost:3000”访问“http://localhost:52340/tools”处的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头请求的资源。
在 chrome 中,在 firefox 中也出现类似错误。
在快速搜索后,我开始使用“Microsoft.AspNetCore.Cors 2.2.0”包以声称可以工作的多种格式添加 cors。但是我的 react 应用程序在尝试获取数据时继续在控制台中返回相同的错误。
我尝试根据操作、特定策略名称、控制器范围设置 CORS,目前我的 startup.cs 中的代码如下。
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.AddCors(options=>
{
options.AddDefaultPolicy(builder =>
{
builder
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowCredentials()
.AllowAnyHeader()
;
});
});
services.AddControllers().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Latest);
}
// 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.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
我看过多篇关于这个主题的博客文章和堆栈溢出问题,这只是 2 个示例。 .NET Core 2 Web API: CORS issues https://weblog.west-wind.com/posts/2016/sep/26/aspnet-core-and-cors-gotchas
但经过多个小时的不同尝试后,我仍然不走运,我不知道我错过了什么。
我怀疑确实存在明显的错误,但我无法弄清楚。希望这里有人能指出我正确的方向
【问题讨论】:
标签: c# reactjs .net-core axios cors