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

时间:2015-07-07 09:50:15

标签: javascript node.js express node-http-proxy node-request

我想代理对新端口的调用,因此我将创建服务器的所有逻辑封装到类似

的函数中
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)

我应该如何避免这个

1 个答案:

答案 0 :(得分: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
  });    
}