node+express 实现简单的服务器代理
1.安装http-proxy-middleware
npm install --save-dev http-proxy-middleware
2.使用
const express = require('express');
const app = express();
const path = require('path')
const proxy = require('http-proxy-middleware')
// 允许所有域名跨域
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
// 跨域请求CORS中的预请求
if (req.method == "OPTIONS") {
// res.send(200); //让options请求快速返回
} else {
next();
}
});
// 服务器代理
app.use('/api', proxy({
target: "http://www.baidu.com",
changeOrigin: true,
pathRewrite: {
"^/api": "/"
}
}))
// 开启静态文件
app.use('/dist', express.static(path.join(__dirname, './dist')))
app.listen(5000, () => {
console.log("服务器启动 5000")
})