我正面临这个问题:
已被CORS策略阻止从源“ http://localhost:5000/api/surpactemp/”访问“ http://localhost:4200”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。
在后端,我尝试了这种方式,但没有成功:
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
我一直在尝试几种方法来使用Microsoft参考进行解决(如下),但到目前为止没有成功。另外,我已经尝试过不在Angular上传递标题对象,然后,我收到错误消息:
请求中没有'Access-Control-Allow-Origin'标头
环境:
后端:Startup.cs
//ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.WithHeaders(HeaderNames.ContentType, "application/json")
.WithMethods("PUT", "DELETE", "GET", "OPTIONS", "POST")
);
});
//Configure
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Frontend:form-service.ts
httpOptions = {
headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'withCredentials': 'false',
// 'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
})
};
return this.httpClient.post('http://localhost:5000/api/surpactemp/', JSON.stringify(data.path), this.httpOptions);
参考:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests
您可以使用代理配置。
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc();
app.UseCors(
options => options.WithOrigins("http://localhost:4200","https://localhost:4200")
.AllowAnyHeader().AllowAnyMethod().AllowCredentials()
);
编辑:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(
options => options.WithOrigins("http://localhost:4200", "https://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}