通过 SSH 隧道访问端点

Accessing endpoint via SSH tunnel

我 运行 在我的本地机器 (localhost) 上创建一个开发项目,它试图通过 SSH 隧道(React JS SPA)从服务器端点加载数据。

当在 Postman 中使用简单的 GET 运行 时,SSH 隧道建立良好并且端点 returns 正确的数据包。

但是当我尝试从我的应用程序访问数据时(尝试获取和 Axios)返回 200,但不幸的是总是返回一个空数组 - 而不是 1k 对象数组。

下面是 2 个简单的请求,其中 'localhost:8912' 是公开和映射的端口 - 在 Postman 中有效。

获取:

fetch("http://localhost:8912/ENDPOINT/")
  .then(res => console.log(res))
  .catch(err => {
    console.log(err);
    return null;
  });

Axios:

axios
  .get("http://localhost:8912/ENDPOINT/")
  .then(data => console.log(data.data))
  .catch(err => {
    console.log(err);
    return null;
  });

结果几乎立即在浏览器中返回,但由于服务器端计算,在 Postman 中需要几秒钟。

欢迎提出任何建议。

尝试用 127.0.0.1

替换 localhost

这可能与浏览器与 Postman 中的地址解析有关。

如果您没有代理,您可以将 axios 与另一个 npm 库结合使用 — tunnel 以建立 HTTPS-over-HTTP 隧道:

    import axios, { AxiosInstance } from 'axios';
    import * as tunnel from 'tunnel';
    const agent = tunnel.httpsOverHttp({
        proxy: {
            host: 'proxy.mycorp.com',
            port: 8000,
        },
    });
    const axiosClient: AxiosInstance = axios.create({
        baseURL: 'https://some.api.com:443',  // here I specify port 443
        httpsAgent: agent,
    });

参考:https://janmolak.com/node-js-axios-behind-corporate-proxies-8b17a6f31f9d

fetch("http://localhost:8912/ENDPOINT/")
  .then(res => return res.json())
  .then(res => console.log(res))
  .catch(err => {
    console.log(err);
    return null;
  });

获取 returns 一个 object as Promise,其中包含各种信息,例如 headers、HTTP 状态等

您有 res.json() 和其他各种可能性。 .json() 将只是 return body 作为 json 内容的承诺。

更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

您可以return数据如下:

  • .arrayBuffer()
  • .blob()
  • .json()
  • .text()
  • .formData()