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

如何在Express的router.get方法中发起HTTP请求

错误原因说明

  • 方案1报错fetch is not defined:Node.js在18.x版本才将fetch纳入默认全局API,低于该版本的Node环境没有内置全局fetch,直接调用就会抛出该错误。
  • 方案2报错未处理error事件:一方面GitHub API要求所有请求必须携带User-Agent请求头,否则会直接拒绝请求;另一方面你没有给https.get绑定error事件监听,请求失败时的异常没有被捕获,才会抛出未处理错误的提示。

可用解决方案

方案A:使用Node原生https模块(无需安装第三方依赖)

直接补全请求头、监听数据和错误事件即可,完整代码如下:

const express = require('express');
const router = express.Router();
const https = require("https");

router.get('/github', function (req, res) {
  // 配置GitHub API请求参数,必须带User-Agent
  const options = {
    hostname: 'api.github.com',
    path: '/users/tmtanzeel',
    headers: {
      'User-Agent': 'My-Express-App' // 此处可自定义为你的应用名称
    }
  }

  https.get(options, (githubRes) => {
    let data = ''
    // 拼接返回的数据流
    githubRes.on('data', (chunk) => {
      data += chunk
    })
    // 数据接收完成后返回给前端
    githubRes.on('end', () => {
      res.setHeader('Content-Type', 'application/json')
      res.send(data)
    })
  }).on('error', (err) => {
    // 捕获请求错误,返回错误信息
    res.status(500).json({
      error: '请求GitHub API失败',
      detail: err.message
    })
  })
});

module.exports = router

方案B:使用fetch(适合Node 18+版本)

如果你的Node版本是18.x及以上,直接调用fetch即可,不需要额外安装依赖:

router.get('/github', async function (req, res) {
  try {
    const githubRes = await fetch('https://api.github.com/users/tmtanzeel', {
      headers: {
        'User-Agent': 'My-Express-App'
      }
    })
    const data = await githubRes.json()
    res.json(data)
  } catch (err) {
    res.status(500).json({
      error: '请求GitHub API失败',
      detail: err.message
    })
  }
});

方案C:使用第三方请求库axios(写法更简洁)

先执行安装命令:npm install axios
然后参考如下代码:

const axios = require('axios')

router.get('/github', async function (req, res) {
  try {
    const { data } = await axios.get('https://api.github.com/users/tmtanzeel', {
      headers: {
        'User-Agent': 'My-Express-App'
      }
    })
    res.json(data)
  } catch (err) {
    res.status(500).json({
      error: '请求GitHub API失败',
      detail: err.message
    })
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:39:01