Node.js 反向代理
反向代理充当服务器和客户端之间的中介,将客户端请求转发到后端服务器,并将响应返回给客户端。
反向代理的作用
| 功能 | 说明 |
|---|---|
| 负载均衡 | 请求分发到多个后端服务器 |
| 高可用性 | 故障转移,某个后端挂了自动切换 |
| 缓存优化 | 缓存静态资源,减轻后端压力 |
| 安全性 | 过滤恶意请求,充当防火墙 |
| 域名/路径重写 | URL 路由和重定向 |
实现(http-proxy-middleware)
bash
npm install http-proxy-middleware配置文件 xm.config.js
js
module.exports = {
server: {
proxy: {
'/api': {
target: 'http://localhost:3000', // 转发地址
changeOrigin: true, // 处理跨域
}
}
}
}主服务器 index.js(端口 80)
js
const http = require('node:http')
const url = require('node:url')
const { createProxyMiddleware } = require('http-proxy-middleware')
const config = require('./xm.config.js')
const server = http.createServer((req, res) => {
const { pathname } = url.parse(req.url)
const proxyList = Object.keys(config.server.proxy)
if (proxyList.includes(pathname)) {
// 匹配到代理路径,转发请求
const proxy = createProxyMiddleware(config.server.proxy[pathname])
proxy(req, res)
return
}
// 其他请求返回静态 HTML
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(html)
})
server.listen(80)后端服务 test.js(端口 3000)
js
http.createServer((req, res) => {
const { pathname } = url.parse(req.url)
if (pathname === '/api') {
res.end('success proxy')
}
}).listen(3000)请求流程
浏览器 → http://localhost:80/api
↓ pathname 匹配代理规则
http-proxy-middleware 转发
↓
http://localhost:3000/api → 返回 'success proxy'