-
-
Save MossTheFox/eb9ede4c622c4ea65493147efad72ff0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createProxyMiddleware } from 'http-proxy-middleware';; | |
import express from 'express'; | |
const app = express(); | |
app.use((req, res, next) => { | |
res.removeHeader('x-powered-by'); | |
console.log(`[${new Date().toLocaleString()}] ${req.ip}, ${req.method} ${req.path}, ${req.headers['user-agent']}`) | |
// 这边可以进行随机的错误模拟。例如: | |
if (Math.random() > 0.8) { | |
res.status(500).send('boom'); | |
return; | |
} | |
next(); | |
}); | |
/** | |
* @see https://www.npmjs.com/package/http-proxy-middleware | |
*/ | |
app.use('/', createProxyMiddleware({ | |
// 👇 代理目标 (按需修改) | |
target: 'http://example.com', | |
changeOrigin: true, | |
// 这里可以修改请求路径 | |
// pathRewrite: (path) => path.replace(/^\/api/, ''), | |
onProxyRes: (pres, req, res) => { | |
// 在这里可以覆盖代理返回数据的响应。例如,修改响应头: | |
// pres.headers['cache-control'] = 'no-cache'; | |
}, | |
onError: (err, req, res, target) => { | |
console.log(err); | |
} | |
})); | |
// 👇 监听的本地端口 | |
app.listen(23330, () => { | |
console.log('Now running on port 23330...'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment