简体   繁体   English

使用 NodeJS 请求 API 的最快方法

[英]Fastest way to request API with NodeJS

I'm trying to request Binance API https://api.binance.com/api/v3/ping in a NodeJS app in order to make some trades.我正在尝试在 NodeJS 应用程序中请求 Binance API https://api.binance.com/api/v3/ping以进行一些交易。 I'm using axios to request the API我正在使用 axios 请求 API

const testBinanceAPIResponseTime = async () => {
  try {
    await axios.get("https://api.binance.com/api/v3/ping");
  } catch (err) {
    throw new Error(err);
  }
};

I added an interceptor to measure response time我添加了一个拦截器来测量响应时间

axios.interceptors.request.use((x) => {
  x.meta = x.meta || {};
  x.meta.requestStartedAt = new Date().getTime();
  return x;
});

axios.interceptors.response.use((x) => {
  console.log(
    `Execution time for: ${x.config.url} - ${
      new Date().getTime() - x.config.meta.requestStartedAt
    } ms`
  );
  return x;
});

My issue is the response time is always around 220 ms wether I deploy my code on Heroku EU or Heroku US.我的问题是响应时间总是在220 ms左右,无论我在 Heroku EU 或 Heroku US 上部署我的代码。 According to "documentation", requests from US should be a way faster (~ 10 ms ) than EU since there is some Binance servers there.根据“文档”,来自美国的请求应该比欧盟更快(约10 ms ),因为那里有一些 Binance 服务器。 Is there a way to improve that response time by using another lib or another pattern?有没有办法通过使用另一个库或其他模式来改善响应时间?

Your Data can not travel faster than the speed of the light.您的数据不能以超过光速的速度传播。 So If you have 3000 km distance that is equal to 3 * 10^6 meters and the speed of light is 3 * 10 ^ 8 meter/second timeTaken = distance/velocity which is 3*10^6 / 3*10^8 =10^-2 (.01 s) which is 10 ms (10 * 10 ^ -3).所以如果你有 3000 公里的距离等于 3 * 10^6 米,光速是 3 * 10 ^ 8 米/秒timeTaken = distance/velocity3*10^6 / 3*10^8 =10^-2 (.01 s) ,即 10 毫秒 (10 * 10 ^ -3)。 So when you count rount trip time that is sent and recieved it will be double 20 ms that is the fastest you can get.因此,当您计算发送和接收的往返行程时间时,它将是您可以获得的最快速度的两倍 20 毫秒。 I have not included routing and other times And also apis have their own response time (processing time of your request).If the heroku server is far away from your binance server even though its in america, you can not get the desired speed.我没有包括路由和其他时间,而且 api 有自己的响应时间(您的请求的处理时间)。如果 heroku 服务器远离您的币安服务器,即使它在美国,您也无法获得所需的速度。

I would start by trying to do a request with Postman for example or a tool to test the real speed of it.例如,我会尝试使用Postman或测试其实际速度的工具来发出请求。

After it, I would not use the axios Npm, use a regular fetch request .之后,我不会使用axios Npm,使用常规的fetch request

Also, check the speed of your Heroku server(the difference between local and on server)另外,检查您的 Heroku 服务器的速度(本地和服务器上的区别)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM