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

如何调试Heroku应用无法发起Yelp API请求的故障?

解决Heroku部署中Yelp API调用超时(H12)及400错误问题

问题现象

  • 应用部署在Heroku平台,MongoDB Atlas用户认证功能正常
  • 调用Yelp API获取附近地点时,前端控制台返回GET https://my-first-trip.herokuapp.com/category/21.3420389/-157.7992015/pizza 503 (Service Unavailable)
  • Heroku CLI显示错误标识:code=H12、desc=Request timeout
  • 仅app.get("/category/:lat/:lng/:searchCategory")路由失效

根因及解决步骤

根因

Heroku配置变量中的API_KEY被错误添加了引号,输入为'key123'(包含单引号),而非正确的纯密钥字符串key123。这导致Yelp API请求的Authorization头格式不符合要求,返回400错误;同时代码中错误处理逻辑未及时正确结束响应,最终引发Heroku的H12请求超时错误。

解决方法

  1. 登录Heroku控制台,进入目标应用的「Settings」页面
  2. 在「Config Vars」区域找到API_KEY变量
  3. 将变量值修改为不带引号的纯密钥字符串(例如从'key123'改为key123)
  4. 重启Heroku应用,确保配置生效

额外优化建议

  • 补全带参数的/category/:lat/:lng/:searchCategory路由定义,确保请求能正确匹配到API处理逻辑:
app.get("/category/:lat/:lng/:searchCategory", (req, res) => {
  const { lat, lng, searchCategory } = req.params;
  const config = {
    method: 'get',
    url: `https://api.yelp.com/v3/businesses/search?latitude=${lat}&longitude=${lng}&categories=${searchCategory}`,
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}` // 注意Yelp API要求Bearer前缀
    }
  };

  axios(config)
    .then((response) => {
      res.json(response.data);
    })
    .catch((error) => {
      console.error('Yelp API请求错误:', error.response?.data || error.message);
      res.status(error.response?.status || 500).json({ message: error.message });
      // 错误时返回明确状态码并结束响应,避免请求挂起超时
    });
});
  • 错误处理时返回对应HTTP状态码和清晰错误信息,防止请求长时间挂起
  • 确认Authorization头符合Yelp API格式要求(需携带Bearer 前缀)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:33:25