【发布时间】:2020-09-02 06:06:44
【问题描述】:
我在 .net 核心中创建了一个简单的 api,并尝试从 react 应用程序访问它,我收到了一个 CORS 错误。我通过关注 CORS with default policy and middleware 部分启用了 cors
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
我的反应应用程序中仍然出现 cors 错误。不完全确定我哪里弄错了。
.net 核心接口
namespace React_NalONE_API
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
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.AddPolicy(name: MyAllowSpecificOrigins,
// builder =>
// {
// builder.WithOrigins("http://localhost/*",
// "https://localhost/*");
// });
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost/*",
"https://localhost/*");
});
});
services.AddControllers();
}
// 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();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
});
}
}
}
反应应用
componentDidMount () {
console.log("The component is now mounted")
this.setState({loading : true})
fetch('https://localhost:44391/agency')
.then(data => data.json())
.then(data => this.setState({data, loading : false}))
}
错误
Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
非常感谢您的帮助 谢谢 回复
【问题讨论】:
-
违反此约束?
Note: The specified URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.来自docs.microsoft.com/en-us/aspnet/core/security/… -
我在哪里违反了约束@nwpie
-
HTTP/Headers/Origin 提到
localhost(或 localhost:8080)将适合架构,而不是 localhost/* 或 localhost/ 。希望有所帮助。
标签: reactjs asp.net-core asp.net-web-api cors