【发布时间】:2020-04-20 16:10:12
【问题描述】:
我有一个基于 .NET Core 作为后端和 Angular 9 作为前端的 REST 服务。功能和交互一直运行良好。今天突然间,在项目中没有任何相关的变化,它就停止了工作。每次我使用登录功能时都会出现异常:
从源 localhost 访问 XMLHttpRequest 已被阻止 通过 CORS 策略:不存在“Access-Control-Allow-Origin”标头 请求的资源。
我的后端允许使用 CORS:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
angular 的登录功能是:
@Injectable()
export class AuthService {
login(credentials) {
sessionStorage.removeItem('token');
this.isBusy = true;
this.http.post<any>(this.loginUrl, credentials, { observe: 'response' }).subscribe(res => {
this.authenticate(res.body);
}, error => {
sessionStorage.removeItem('token');
this.router.navigate(['/logout'])
})
}
authenticate(res) {
sessionStorage.setItem('token', res);
this.router.navigate(['/']);
}
}
我不明白为什么如果它运行了几个月后它突然停止运行。请指教。
【问题讨论】:
-
ASP.NET Core 应用程序可能已经开始抛出错误,导致返回 500。在这种情况下,可能没有设置 CORS 标头。
标签: c# angular asp.net-core angular7 angular9