17

I post a form with file (enctype="multipart/form-data") to node.js (express.js framework) and just want to send this same post request like it is just to different server. what is the best approach in node.js?

vitulicny
  • 321
  • 2
  • 11

3 Answers3

9

remove express.bodyParser and try pipes like these:

req.pipe(request('http://host/url/')).pipe(res)
IvanM
  • 2,913
  • 2
  • 30
  • 30
7

You could try it with Mikeal's Request for Node.js (https://github.com/mikeal/request). It would be something like:

app.post('/postproxy', function(req, res, body){
    req.pipe(request.post('http://www.otherserver.com/posthandler',body)).pipe(res);
});
Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
  • since the req is in my case expres.js request, it seems not to have a pipe method. the problem what i have is that i use this bodyParser app.use(express.bodyParser()); – vitulicny Feb 20 '12 at 13:23
  • , so when the request is parsed as well. i would like to just grab the whole request, which i got from express and pipe(reposted) it to my other http://mywebserver.com/mywebservice. the problem is more complicated for me, since the post is multipart/form-data and includes a file. According to documentation i am not sure what the parser does with a multipart/form-data request. I can repost simple application/x-www-form-urlencoded request easily using my current proxy. thank you. – vitulicny Feb 20 '12 at 13:32
  • I think node.js 0.5 and newer return stream from .pipe(), so if you have older than this you'd need to do something like: var x = request('http://www.otherserver.com/posthandler') req.pipe(x) x.pipe(resp) I'm not sure about the multipart/form-data issue. – Carol Skelly Feb 20 '12 at 14:02
  • This is not working for me. API gets time out. How can I send/forward the response of /posthandler to /postproxy ? – Farhan Ghumra Apr 25 '19 at 12:19
  • 1
    It worked for me. I was using multer for multipart//form-data request. I don't have to use that, I need to send request intact without any changes. Multer was parsing the request and hence it was not being forwarded. – Farhan Ghumra Apr 25 '19 at 12:39
0

Since https://github.com/mikeal/request is deprecated, here is the solution using http module from node:

app.post('/proxy', (request, response, next) => {
  const options = {
    host: 'destination_host',
    port: 'destination_port',
    method: 'post',
    path: '/destination_path',
    headers: request.headers
  };
  request.pipe(http.request(options, (destinationResponse) => {
    destinationResponse.pipe(response);
  }))
    .on('error', (err) => {
      // error handling here
    })
}

In order to proxy files from multipart/form-data I had to use the original request headers.

bognix
  • 33
  • 6