【问题标题】:Angular Service not hitting API endpointAngular Service 未命中 API 端点
【发布时间】:2020-04-22 09:41:45
【问题描述】:

我正在尝试测试一项名为 vpnblocker 的服务,该服务将检测用户是否使用 VPN。我正在关注documentationAPI variables,并且我已经设置了我的角度服务来调用 API,但它从不返回任何值。 ngOnInit 中的 console.logs 之间没有任何输出。这是为什么呢?

角度分量

ngOnInit() {
    console.log("VPN IS RUNNING FUNCTION START");
    this.loginService.vpnIsRunning().subscribe(res => {
      console.log(res);
    });
    console.log("VPN IS RUNNING FUNCTION END");

  }

角度服务

    vpnIsRunning() {
    let format = "json";
    let ip = "45.87.214.236";
    return this.http
      .get<{
        posts: any;
      }>(`http://api.vpnblocker.net/v2/${format}/${ip}`)
      .pipe(
        map(retrievedData => {
          return {
            posts: retrievedData.posts.map(post => {
              return {
                status: post.status,
                ipaddress: post.ipaddress,
                msg: post.msg
              };
            })
          };
        })
      );
  }

控制台

Access to XMLHttpRequest at 'http://api.vpnblocker.net/v2/json/72.238.50.117' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
login.component.ts:60 HTTP Error HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://api.vpnblocker.net/v2/json/72.238.50.117", ok: false, …}
zone-evergreen.js:2952 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://api.vpnblocker.net/v2/json/72.238.50.117 with MIME type text/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.

【问题讨论】:

  • 在 ngOnInit 同步命令异步执行的两个 console.logs 之间不会发布任何内容。 console.log 的输出是在之后发生还是根本不发生?您还可以查看网络调用是否实际在您的开发人员工具中执行?
  • 看起来它与 cors 有某种关系?我认为 cors 只在服务器端配置? console.logs 出现在页面加载时,中间没有任何内容。

标签: angular


【解决方案1】:

要进行跨域请求,您需要使用服务的 HttpClientJsonpModule 和 jsonp 方法。

更多内容到这里https://angular.io/guide/http#making-a-jsonp-request

【讨论】:

    【解决方案2】:

    你应该抓住http get。因为你有一个 httpError。

    例子:

    .subscribe(
        res => console.log('HTTP response', res),
        err => console.log('HTTP Error', err),
        () => console.log('HTTP request completed.')
    );
    

    更新

    https://vpnblocker.net/usage/http-status-codes/

    Forbidden – This occurs when you try requesting from the API server using SSL (HTTPS) without the Basic or Professional package.

    如果您在 http 或 localhost 上进行测试,您将收到此错误。

    使用 ngrok 在 https 上为您的本地主机提供服务。

    【讨论】:

    • 我查看了 angular http 标头文档,但在将标头添加到 api 调用后仍然出现相同的错误。 pastebin.com/dq9yhFnZ你知道这是为什么吗?我在上面添加了控制台输出
    • 这是否意味着当我部署到 aws s3 来托管我的 Angular 应用程序时问题会消失?
    • 您可以通过将http:localhost 转发到https:ngrok..... 来进行本地测试。请参阅 ngrok 上的文档。但是是的,它可能会在 https 上运行。
    猜你喜欢
    • 2019-02-07
    • 2020-04-14
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多