代理请求超过时间提供错误

Proxy request more than on time provide error

我想代理对新端口的调用,所以我将创建服务器的所有逻辑封装到一个函数中,例如

var appRouter = express.Router();
app.use(appRouter);


appRouter.route('*')
    .get(function (req, res) {
        proxyRequest(req, res)
    }

在代理请求函数中我放了下面的代码

function proxyRequest(req, res) {

    httpProxy = require('http-proxy');
    var proxy = httpProxy.createProxyServer({});
    var hostname = req.headers.host.split(":")[0];

    proxy.web(req, res, {
        target: 'http://' + hostname + ':' + 5000
    });
    http.createServer(function (req, res) {
        console.log("App proxy new port is: " + 5000)
        res.end("Request received on " + 5000);
    }).listen(5000);

}

问题是,当我第一次调用时,我看到代理工作正常并在新服务器端口 5000 上监听,当我第二次访问浏览器时出现错误

Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1146:14)

我应该如何避免这种情况

proxyRequest 函数中删除代理服务器创建逻辑

试试这个:

httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
http.createServer(function (req, res) {
    console.log("App proxy new port is: " + 5000)
    res.end("Request received on " + 5000);
}).listen(5000);

function proxyRequest(req, res) {
  var hostname = req.headers.host.split(":")[0];
  proxy.web(req, res, {
    target: 'http://' + hostname + ':' + 5000
  });    
}