反向代理(Reverse Proxy)是一种网络通信模式,它充当服务器和客户端之间的中介,将客户端的请求转发到一个或多个后端服务器,并将后端服务器的响应返回给客户端。
用到的库
http-proxy-middleware
npm install http-proxy-middleware
根目录自定义配置文件
xm.config.js
配置proxy代理
module.exports = {
server:{
proxy:{
//代理的路径
'/api': {
target: 'http://localhost:3000', //转发的地址
changeOrigin: true, //是否有跨域
}
}
}
}
index.js 实现层
const http = require('node:http');
const fs = require('node:fs')
const url = require('node:url')
const html = fs.readFileSync('./index.html') //给html文件起个服务
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
}
console.log(proxyList)
res.writeHead(200, {
'Content-Type': 'text/html'
})
res.end(html) //返回html
})
server.listen(80) //监听端口
test.js 因为我们从80端口转发到3000端口
const http = require('node:http')
const url = require('node:url')
http.createServer((req, res) => {
const {pathname} = url.parse(req.url)
if(pathname === '/api'){
res.end('success proxy')
}
}).listen(3000)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
fetch('/api').then(res=>res.text()).then(res=>{
console.log(res);
})
</script>
</body>
</html>
这样就从80代理到了3000端口 并且无跨域