结论
正向代理隐藏真实客户端,反向代理隐藏真实服务端
- 正向代理
- 反向代理
- 使用
http-proxy-middware实现正向代理达到跨域的目的
const http = require('http')
const proxy = require('http-proxy-middleware')
http.createServer((req, res) => {
let url = req.url
res.writeHead(200, {
'Access-Control-Allow-Origin': '*'
})//使用CORS解决前端页面跨域到该8080port
/*
1、api:是一个暗号,进行代理
2、pathRewrite:取消api的路径,实现的功能:
无pathRewrite:localhost:8080/api/path ==>m.lagou.com/api/path
有pathRewrite:localhost:8080/api/path ==>m.lagou.com/path
*/
if (/^/api/.test(url)) {
let apiProxy = proxy('/api', {
target: 'https://m.lagou.com',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
})
// http-proy-middleware 在Node.js中使用的方法
apiProxy(req, res)
} else {
switch (url) {
case '/index.html':
res.end('index.html')
break
case '/search.html':
res.end('search.html')
break
default:
res.end('[404]page not found.')
}
}
}).listen(8080)