【问题标题】:How to convert Angular clientHttp to node.js如何将 Angular clientHttp 转换为 node.js
【发布时间】:2024-01-07 06:51:01
【问题描述】:

我有以下在 Angular 中工作的代码,并希望将其转换为节点,有人可以帮忙吗?

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

private getDeviceIP(){
    this.clientHttp.get("http://api.ipify.org/?format=json").subscribe((res:any)=>{
            this.userIpAddress = res.ip;            
        });
}

干杯

【问题讨论】:

    标签: javascript node.js angular httprequest http-get


    【解决方案1】:

    如果您想在 NodeJS 中使用该逻辑,请注意 NodeJS 服务器是发送请求的服务器,因此您将获得他的 IP 地址,而不是客户端的 IP 地址。

    如果你还想在NodeJs中实现同样的逻辑,你可以使用axios(基于Promise的HTTP客户端),像这样:

    const axios = require('axios');
    
    const getDeviceIP = (req, res, next) => {
      axios({
        method: 'get',
        url: 'http://api.ipify.org/?format=json'
      }).then((response) => {
        return res.status(200).json({ success: true, ip_address: response.data.ip })
      }).catch((error) => {
        return res.status(400).json({ success: false, error })
      });
    }
    

    【讨论】:

      【解决方案2】:

      根据您的用例(请参阅下面的警告),这已经转换为 Node!

      如果您使用@angular/commontypescriptxmlhttprequest 包,您可以使用以下:

      import { XMLHttpRequest } from 'xmlhttprequest';
      import { HttpClient, HttpXhrBackend } from '@angular/common/http';
      
      // Your unmodified class
      class Main {
        userIpAddress: any;
      
        constructor (private clientHttp: HttpClient) {}
      
        getDeviceIP () {
          this.clientHttp.get('http://api.ipify.org/?format=json').subscribe((res: any) => {
            this.userIpAddress = res.ip;
          });
        }
      }
      
      // Manually perform the dependency resolution
      const backend = new HttpXhrBackend({
        build: (): XMLHttpRequest => new XMLHttpRequest()
      });
      const client = new HttpClient(backend);
      const main = new Main(client);
      
      // Run it!
      main.getDeviceIP();
      

      可以转译:

      npx tsc --lib dom,es2015 main.ts
      

      并运行:

      node main.js
      

      警告

      注意dom 在转译中作为库的使用;这是必需的,因为@angular/common/http 子包没有与@angular/core 的DOM 相关部分正确解耦。为了使用带有 Node 兼容后端的 HttpClient 发出请求,这很好,但尝试转换更多与 DOM 相关的任务可能会遇到问题。

      【讨论】: