如何在nodejs代理请求中获取响应对象

时间:2014-02-11 08:51:22

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

我有一个nodejs程序,它将传入的请求定向到couchDb服务器。

这是代码

/*!
 * Middleware for forwarding a request to CouchDB.
 */

/**
 * Module dependencies.
 */

var httpProxy = require('http-proxy'),
    util = require('./util');

// Set max sockets opened by proxy
var maxSocks = process.env.MAX_SOCKETS || 2048;

// Set timeout (ms) for proxy requests. Ideally this should be less than 30000ms which is Heroku timeout
var timeout = process.env.TIMEOUT || 25000;

httpProxy.setMaxSockets(maxSocks);
httpProxy.timeout = timeout;

module.exports = function(couch) {
    var proxy = new httpProxy.HttpProxy(couch),
        couchTarget = couch.target;

    return function(req, res, next) {
        console.log('Received request: ' + req.url);

        req.headers['host'] = couchTarget.host + ':' + couchTarget.port;
        req.headers['authorization'] = couch.credentials;
        req.headers['x-forwarded-ssl'] = util.isSecureForwardedRequest(req);
        var forwardedFor = req.headers['x-forwarded-for'];
        req.headers['x-real-ip'] = forwardedFor
            ? forwardedFor.split(',',1)[0]
            : req.connection.remoteAddress;
        req.url = couch.path + req.url;

        console.log('Proxying to: ' + req.url);

        var startTime = new Date().getTime();

        var res = proxy.proxyRequest(req, res);

        console.log(" Response is " + res + req);

        return res;
    }
}

res对象始终未定义。如果响应为404,我需要处理一个案例。我们如何使用http-proxy模块

来做到这一点

1 个答案:

答案 0 :(得分:1)

我认为proxy.proxyRequest(req, res);不会返回任何值,并直接更改参数'res' 因此,只需将代码从var res = proxy.proxyRequest(req, res);更改为proxy.proxyRequest(req, res);

即可