NodeJS使用express框架如何将指定URL内容作为响应体返回
问题根因
你当前代码的逻辑是直接把URL字符串作为文本传入res.send(),express不会主动发起请求获取该URL对应的远端内容,只会把字符串本身作为响应体返回。
解决方法
你需要先主动请求目标URL的内容,再把内容返回给客户端,以下是两种实现方案:
方案1:使用axios第三方库(写法更简洁,适配场景广)
- 首先安装依赖:
npm install axios - 修改后的server.js代码:
const express = require('express'); const axios = require('axios'); const app = express(); app.get('/', async (req, res) => { try { // 以流的形式请求目标内容,减少内存占用,兼容图片等二进制资源 const targetResponse = await axios.get('https://http.cat/200', { responseType: 'stream' }); // 透传响应头保证客户端能正确识别内容格式 res.set(targetResponse.headers); // 将远端内容流直接输出到客户端响应 targetResponse.data.pipe(res); } catch (error) { res.status(500).send('资源请求失败:' + error.message); } }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`Server listening on port ${PORT}...`); });
方案2:使用Node原生https模块(无需额外依赖)
直接修改server.js代码即可:
const express = require('express'); const https = require('https'); const app = express(); app.get('/', (req, res) => { https.get('https://http.cat/200', targetResponse => { res.set(targetResponse.headers); targetResponse.pipe(res); }).on('error', error => { res.status(500).send('资源请求失败:' + error.message); }); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`Server listening on port ${PORT}...`); });
注意事项
- 如果目标URL返回的是纯文本内容,可以把
responseType改成text,直接拿到内容字符串后再通过res.send()返回即可。 - 如果目标URL是HTTP协议,把
https模块替换成http模块即可。
内容的提问来源于stack exchange,提问作者Bruno Lobo
相关产品推荐
相关产品推荐

