我正在为角度为7的黑客新闻创建接口。通常我使用可用的公共API,但对于登录服务则不可用。
我正在尝试进行POST呼叫,就像针对HN的OpenSource 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));
我该怎么解决?
答案 0 :(得分:1)
您不能使用CORS对服务器进行Ajax调用。浏览器检查服务器的CORS策略。
Android / IOS应用程序不是浏览器,它可以拨打电话而不会被阻止。
如果您拥有自己的服务器,则可以向服务器发出请求,服务器继而向Harker Ranks服务器发出请求,并将响应返回到Angular应用。
使用curl请求获取页面。 用您的凭据替换acct和pw。
curl -L -X POST \
https://news.ycombinator.com/login \
-H 'Access-Control-Allow-Headers: X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-H 'cache-control: no-cache' \
-d 'acct=username&pw=password&goto=%20news'
答案 1 :(得分:0)
从Web域向Web API域发出请求时,我遇到了相同的问题,并通过以下方式解决了相同的问题:
这将解决跨域问题。
答案 2 :(得分:0)
针对CORS问题的解决方案是使用代理,对于开发中的angular,您可以将Angular CLI服务器用作代理(https://stackoverflow.com/questions/50021126/implementation-of-proxy-server-in -angular4-5? rq = 1)。
这是我的proxy.conf.json:
{
"/hackernews/*": {
"target": {
"host": "news.ycombinator.com",
"protocol": "https:",
"port": 443
},
"secure": false,
"logLevel": "info",
"changeOrigin": true,
"pathRewrite": {"^/hackernews" : ""}
}
}
编辑package.json的“开始”以查看下方
"start": "ng serve --proxy-config proxy.conf.json"
不幸的是,对于实际的构建,没有如此简单的解决方案,可以在生产服务器上指定代理,具体取决于所使用的服务器。