背景:前端代码在浏览器里面运行,由于浏览器的同源策略,不能直接发送跨域请求,所以,前端要做一个反向代理,解决跨域问题
实现方式:node,nginx,http-proxy-middleware,http-proxy等,本文主讲http-proxy-middleware和http-proxy这2中方式
1.http-proxy-middleware如何做反向地理
1.1安装依赖
npm i http-proxy-middleware
1.2http-proxy-middleware的常用api
const { createProxyMiddleware } = require("http-proxy-middleware")
const app = require("express")
const proxyArr = [
{
proxyPath: '/api',
host: "http://localhost:6000"
}
]
proxyArr.forEach(({ proxyPath, host }) => {
app.use(proxyPath, createProxyMiddleware({
target: host, //目标url
ws: true, //是否改变原始主机头为目标url,默认为false
changeOrigin: true, //是否允许跨域
pathRewrite: { //重写路径
["^" + proxyPath]: proxyPath
}
}))
})
参考文档:https://github.com/chimurai/http-proxy-middleware
2.http-proxy详解
2.1安装http-proxy模块
npm i http-proxy
2.2http-proxy的api详解
const httpProxy = require("http-proxy"); //创建http-proxy实例
const http = require("http")
const server = httpProxy.createServer({})
http.createServer((req, res) => {
server.web(req, res, { //代理http协议
target: "http://localhost:4000",
ws: false,
ssl: { //如果target代理的是https,则要添加ssl配置项目,(https的公钥和私钥)
key: "",
cert: ""
},
secure: true //是否安全
})
}).listen(3000)
server.web代理的是http和https
server.ws代理的websoket
//监听服务端请求数据
server.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); //设置请求头
});