Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse proxy to CouchDB hangs on POST and PUT in Node.js

I use request to implement the following reverse proxy to CouchDB in Express:

app.all(/^\/db(.*)$/, function(req, res){
  var db_url = "http://localhost:5984/db" + req.params[0];
  req.pipe(request({
    uri: db_url,
    method: req.method
  })).pipe(res);
});

When making GET requests, it works: requests go from the client to node.js to CouchDB and back again successfully. POST and PUT requests hang indefinitely. Log statements run until the proxy, but CouchDB doesn't indicate receipt of the request. Why is this happening, and how can it be fixed?

like image 224
garbados Avatar asked Jul 07 '13 20:07

garbados


1 Answers

Express' bodyparser middleware modifies the request in a way that causes piping to hang. Not sure why, but you can fix it by making your proxy into middleware that catches before the bodyparser. Like this:

// wherever your db lives
var DATABASE_URL = 'http://localhost:5984/db';

// middleware itself, preceding any parsers
app.use(function(req, res, next){
  var proxy_path = req.path.match(/^\/db(.*)$/);
  if(proxy_path){
    var db_url = DATABASE_URL + proxy_path[1];
    req.pipe(request({
      uri: db_url,
      method: req.method
    })).pipe(res);
  } else {
    next();
  }
});
// these blokes mess with the request
app.use(express.bodyParser());
app.use(express.cookieParser());
like image 174
garbados Avatar answered Sep 24 '22 22:09

garbados