我面临这个问题:
访问 XMLHttpRequest 位于 'http://localhost:5000/api/surpactemp/ http://localhost:5000/api/surpactemp/'从原点'http://本地主机:4200 http://localhost:4200' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。
在后端,我尝试了这种方法,但没有成功:
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
我一直在尝试使用 Microsoft 参考(如下)的多种方法来解决问题,但是到目前为止还没有成功。
另外,我已经尝试不在 Angular 上传递 headers 对象,然后,我收到错误:
请求中不存在“Access-Control-Allow-Origin”标头
环境:
Backend:启动.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: 表单服务.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://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#preflight-requests