【发布时间】:2021-04-27 00:15:12
【问题描述】:
我在从 Angular 发送身份验证标头 jwt 令牌时遇到了以下问题。 从源“http://localhost:4200”访问“http://localhost:52278/api/user/signup”的 XMLHttpRequest 已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头在请求的资源上。
.Net Core
var origins = Configuration["CorsUrl"].Split(",");
services.AddCors(options =>
{
options.AddPolicy("BasePolicy",
builder =>
{
builder
.AllowAnyMethod()
.WithOrigins(origins)
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
app.UseAuthorization();
app.UseCors("BasePolicy");
app.UseHttpsRedirection();
角度:
signUpAdmin(data: AdminSignUpModel) {
return this.httpClient.post('user/signup', data,this.getCommonOptions());
}
private _token: string = localStorage.getItem('auth_token');
protected getCommonOptions() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
Authorization: `Bearer ${this._token}`,
})
};
return httpOptions;
}
【问题讨论】:
标签: angular asp.net-core