0

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

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)

我应该如何避免这种情况

4

1 回答 1

1

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
  });    
}
于 2015-07-07T10:29:22.917 回答