You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多API数据集中到单一API端点实现及问题排查:/coingeckotest返回null但终端可获取数据

解决API聚合返回null的问题

嘿,我瞅了你的代码,发现两个核心问题导致你访问/coingeckotest时拿到null,咱们一步步解决:

问题1:异步函数没返回实际数据

你的四个数据获取函数(比如datauniswap)里,axios.get()的then回调只做了console.log(res.data),却没把res.data返回出去。这就导致await datauniswap()拿到的是undefined——因为then回调默认返回undefined,你的函数最后也就返回了这个值。

问题2:响应方法调用错误

你写的res.json[exchangeone, exchangetwo, exchangethree, exchangequattro]是错的,res.json()是Express的响应方法,得用括号调用,把要返回的数据传进去,不是用数组下标语法。

修正后的完整代码

const axios = require('axios');
const express = require('express');
const server = express();

async function datauniswap() { 
  const res = await axios.get('https://api.coingecko.com/api/v3/exchanges/uniswap/tickers');
  console.log(res.data);
  return res.data;
} 

async function datasushiswap() { 
  const res = await axios.get('https://api.coingecko.com/api/v3/exchanges/sushiswap/tickers');
  console.log(res.data);
  return res.data;
} 

async function datacurvefinance() { 
  const res = await axios.get('https://api.coingecko.com/api/v3/exchanges/curve/tickers');
  console.log(res.data);
  return res.data;
} 

async function dataquickswap() { 
  const res = await axios.get('https://api.coingecko.com/api/v3/exchanges/quickswap/tickers');
  console.log(res.data);
  return res.data;
} 

server.get('/coingeckotest', async (req, res) => { 
  // 用Promise.all并行发起请求,比挨个await快很多
  const [exchangeone, exchangetwo, exchangethree, exchangequattro] = await Promise.all([
    datauniswap(),
    datasushiswap(),
    datacurvefinance(),
    dataquickswap()
  ]);
  const cacheTime = Date.now(); 
  // 正确调用res.json返回数据,这里把缓存时间也一起返回了
  res.json({
    cacheTime,
    exchanges: [exchangeone, exchangetwo, exchangethree, exchangequattro]
  });
});

// 记得启动服务器,端口可以自己改
server.listen(3000, () => console.log('Server running on port 3000'));

额外优化点

我把四个异步请求改成了Promise.all并行执行,这样四个API请求可以同时发起,不用等前一个完成再做下一个,能大幅提升接口响应速度。

内容的提问来源于stack exchange,提问作者Usual Token

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 22:07:46