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

Node.js中如何在两个API间传递变量?非Ajax方案求助

问题根源

你遇到的核心问题是异步操作的执行顺序错误:getPlaces和getGeo都是异步API请求,你同时调用它们时,getPlaces会先发起请求,但此时lat和lng还没被getGeo的回调赋值(API请求需要时间返回结果),所以第一个API拿到的是undefined,undefined,自然无法正常工作。

另外还有两个细节问题:

  • 不需要用JSON.stringify把坐标转成字符串,直接用数字拼接成参数字符串即可
  • 全局变量容易导致逻辑混乱,建议通过函数返回值传递数据,不要依赖全局变量
修复后的代码
app.get("/", async (req, res) => {
  try {
    // 先获取地理坐标,确保拿到值后再执行下一步
    const { lat, lng } = await getGeo();
    // 用拿到的坐标请求附近咖啡馆数据
    const places = await getPlaces(lat, lng);
    // 渲染页面
    res.render("index", { places });
  } catch (error) {
    console.error(error);
    res.status(500).send("服务器出错");
  }
});

// 改写getGeo,返回Promise直接传递坐标数据
function getGeo() {
  const options = {
    method: 'GET',
    url: 'https://trueway-geocoding.p.rapidapi.com/Geocode',
    params: { address: 'toronto, ontario', language: 'en' },
    headers: {
      'X-RapidAPI-Key': '49b3d82605msh88c216e62d3770cp13f60cjsnec91372acf2e',
      'X-RapidAPI-Host': 'trueway-geocoding.p.rapidapi.com'
    }
  };

  return axios.request(options).then(response => {
    const location = response.data.results[0].location;
    return {
      lat: location.lat,
      lng: location.lng
    };
  });
}

// 改写getPlaces,接收lat和lng作为参数,返回Promise
function getPlaces(lat, lng) {
  const options = {
    method: 'GET',
    url: 'https://trueway-places.p.rapidapi.com/FindPlacesNearby',
    params: { location: `${lat},${lng}`, type: 'cafe', radius: '150', language: 'en' },
    headers: {
      'X-RapidAPI-Key': '49b3d82605msh88c216e62d3770cp13f60cjsnec91372acf2e',
      'X-RapidAPI-Host': 'trueway-places.p.rapidapi.com'
    }
  };

  return axios.request(options).then(response => {
    console.log(response.data);
    return response.data;
  });
}
关键改动说明
  • 路由处理函数改为async,用await确保先完成getGeo获取坐标,再执行getPlaces,彻底解决异步顺序问题
  • 移除全局变量lat和lng,通过函数返回值传递数据,避免全局变量带来的逻辑混乱
  • getGeo和getPlaces都返回Promise,配合await让异步代码逻辑更清晰,像同步代码一样易读
  • 去掉JSON.stringify,直接用数字拼接location参数,符合API的参数格式要求
  • 统一用try/catch捕获错误,避免单个API请求失败导致页面无响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 03:54:12