我想用 http-proxy-middleware 和 express 配置代理。规则是主机名的映射,例如:
http://123.com >> http://localhost:3000/123
http://456.com >> http://localhost:3000/abc
我试过这样:
import express from 'express';
import http from 'http';
import proxy from 'http-proxy-middleware';
const app = express();
app.use( async function (req, res) {
let direction = 'http://localhost:3000';
console.log('hostname: ', req.hostname);
console.log('originalUrl: ', req.originalUrl);
if (req.hostname == '123.com') {
direction = `http://localhost:3000/123${req.originalUrl}`;
}
if (req.hostname == '456.com') {
direction = `http://localhost:3000/abc${req.originalUrl}`;
}
return await proxy({ target: direction, changeOrigin: false })
});
const server = http.createServer(app);
app.set('port', '127.0.0.1');
server.listen(9999, '0.0.0.0');
但它不起作用。