【发布时间】:2019-01-31 05:38:28
【问题描述】:
这个问题已经发布了很多次,但我尝试了几种解决方案,但它们都不适合我。我正在制作一个 API 服务,需要使用基本身份验证来获取承载令牌以用于其他端点。 API 是用 .NET Core 编写的。
我的代码很简单:
private GetToken() {
let delta = new Date().getTime() - this.tokenTimestamp.getTime();
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, content-type',
'Authorization': 'Basic ' + btoa(this.user + ':' + this.pass)
})
};
console.log(options);
if (delta >= 60000) {
this.http.post<Response>(this.url + '/api/Auth/Token/', { username: this.user, password: this.pass }, options)
.subscribe(
(val) => {
console.log("POST call successful value returned in body", val);
},
response => {
console.log("POST call in error", response);
},
() => {
console.log("The POST observable is now completed.");
});
}
}
非常感谢您的帮助!
【问题讨论】:
-
CORS 应该在服务器而不是客户端处理。您无能为力,您需要更新您的 API 以发送
access-control-allow-origin标头 -
我正在从 Postman 和 SQL Server 进行测试,并且 POST 运行良好......我认为这是我在 Angular(客户端)中做错的事情。
-
postman 和 sql server 不使用客户端 JS 发送请求,这就是 CORS 的问题.. 这就是本网站上所有答案都告诉你要做的事情
标签: angular api post .net-core angular6