我正在使用 Angular 7 为黑客新闻创建一个界面。通常我使用可用的公共 API,但对于登录服务,它们不可用。
我正在尝试进行 POST 调用,正如 HN 的开源 Android 客户端应用程序所做的那样,特别是在此文件中:https ://github.com/hidroh/materialistic/blob/master/app/src/main/java/ io/github/hidroh/materialistic/accounts/UserServicesClient.java到 url https://news.ycombinator.com/login,设置用户名、密码和重定向作为参数。
不幸的是,我的请求被 CORS 政策阻止了。
我用 Postman 进行了测试,结果却完美无缺。
这是我的代码:
const payload = {
'acct': 'username',
'pw': 'password',
'goto': 'news'
};
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE, HEAD',
'Access-Control-Allow-Headers': 'X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Access-Control-Max-Age': '1728000',
})
};
console.log('Try login');
this.http.post('https://news.ycombinator.com/login', payload, httpOptions)
.pipe(
tap(
data => console.log(data),
error => console.log(error)
)
).subscribe(result => console.log(result));
我该如何解决?