如何在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
相关产品推荐
相关产品推荐

