【发布时间】:2019-10-18 03:26:03
【问题描述】:
当我从客户端应用程序调用我的 API 方法时,我收到以下错误。我正在使用 .NET Core v2.1.6 和 .NET SDK v2.1.502,我的客户端应用程序正在使用 Angular v5.2.0
在“http://localhost:5000/api/auth/login”访问 XMLHttpRequest 来自原点“http://localhost:4200”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: 预检请求不允许重定向。
我尝试了一种不同的方法,即在 startup.cs 中使用自定义 cors 策略。我可以使用邮递员轻松地从 API 获取数据,但从客户端应用程序中却没有。
我的 Startup.cs 函数:
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.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed((host) => true)
.AllowCredentials();
}));
services.AddScoped<IAuthRepository, AuthRepository>();
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
//app.UseCors(x => x.WithOrigins("http://localhost:4200/").AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.UseMvc();
app.UseCors("CorsPolicy");
}
在我的客户端应用程序中使用此服务来验证输入数据:
export class AuthService {
baseUrl = 'http://localhost:5000/api/auth/';
userToken: any;
//
constructor(private http: Http) { }
login(model: any) {
const headers = new Headers({ 'content-type': 'application/json' });
const options = new RequestOptions({ headers: headers });
return this.http.post(this.baseUrl + 'login', model, options).map((response: Response) => {
const user = response.json();
if (user) {
localStorage.setItem('token', user.tokenString);
}
this.userToken = user.tokenString;
});
}
}
【问题讨论】:
-
从这篇文章中我可以假设这是因为我使用“Content-Type”“Application/json”。那我应该用什么。或者如果我使用它,我需要做什么?
-
使用浏览器开发工具中的网络窗格检查对 OPTIONS 预检请求的响应。检查
Location标头,并查看它试图将请求重定向到哪个 URL。然后更改前端 JavaScript 代码中的 URL 以适应Location标头的值。它可以像 URL 中的尾部斜杠一样简单——例如,您可能需要将 URL 更改为http://localhost:5000/api/auth/login/(注意尾部斜杠)而不是http://localhost:5000/api/auth/login(没有尾部斜杠)您的代码当前的 URL将请求发送到。
标签: angular cors xmlhttprequest asp.net-core-2.0