1

我正在使用 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));

我该如何解决?

4

3 回答 3

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'

于 2019-02-15T11:25:28.907 回答
0

我在从 Web 域向 Web API 域发出请求时遇到了同样的问题,并通过以下方式解决了同样的问题:

  1. 在 web api 配置文件中添加以下配置以启用 HTTP 请求并允许客户标头: 在此处输入图像描述

  2. 创建一个名为 crossdomain.xml 的 XML 文件,并将此文件添加到 Web 或应用项目的根位置。 在此处输入图像描述

  3. 另外,在 web 或 app 项目的配置文件中添加如下配置: 在此处输入图像描述

这将解决跨域问题。

于 2019-02-18T05:57:21.077 回答
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"

不幸的是,对于实际构建没有这样简单的解决方案,可以在生产服务器上指定代理,具体取决于使用的服务器。

于 2019-02-19T09:19:08.993 回答