Node.js通用网站代理问题:目标URL重复跳转修复求助
解决Node.js代理URL重复跳转问题
问题场景
开发通用Node.js代理时遇到URL重复跳转:访问localhost:3000/google.com,实际跳转至google.com/google.com,所有域名均存在该问题。希望在不更换http-proxy模块的前提下修复代码。
原代码
const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer(); const PORT = process.env.PORT || 3000; require('http').createServer((req, res) => { const targetUrl = req.url.slice(1).replace(/^https?:\/\//, ''); // remove leading slash and protocol prefix console.log(targetUrl) proxy.web(req, res, { target: `http://${targetUrl}`, // add the protocol back in }); }).listen(PORT, () => { console.log(`Proxy server running on port ${PORT}`); });
问题原因
代理请求时,req.url仍保留原始路径(如/google.com),http-proxy会将该路径直接拼接到目标域名后,导致google.com + /google.com的重复路径。
修复方案
核心是重置req.url为目标域名对应的实际路径,拆分请求中的域名和路径部分,避免路径拼接错误。同时支持http/https协议和带路径的目标请求。
修复后代码
const httpProxy = require('http-proxy'); const proxy = httpProxy.createProxyServer(); const PORT = process.env.PORT || 3000; require('http').createServer((req, res) => { // 移除开头斜杠,获取完整目标字符串 const fullTarget = req.url.slice(1); let protocol = 'http://'; let targetPath = ''; let targetDomain = fullTarget; // 识别并提取协议前缀 if (fullTarget.startsWith('http://')) { protocol = 'http://'; targetDomain = fullTarget.slice(7); } else if (fullTarget.startsWith('https://')) { protocol = 'https://'; targetDomain = fullTarget.slice(8); } // 拆分域名与路径部分 const domainSplit = targetDomain.split('/'); if (domainSplit.length > 1) { targetDomain = domainSplit[0]; targetPath = `/${domainSplit.slice(1).join('/')}`; } // 重置req.url为目标路径(无路径则设为/) req.url = targetPath || '/'; // 拼接完整目标地址 const target = `${protocol}${targetDomain}`; proxy.web(req, res, { target }); }).listen(PORT, () => { console.log(`Proxy server running on port ${PORT}`); });
效果验证
- 访问
localhost:3000/google.com→ 代理至http://google.com/ - 访问
localhost:3000/https://github.com/nodejs/node→ 代理至https://github.com/nodejs/node - 访问
localhost:3000/baidu.com/s?wd=test→ 代理至http://baidu.com/s?wd=test
内容的提问来源于stack exchange,提问作者I will get tableflipped
相关产品推荐
相关产品推荐

