vitulicny
vitulicny

Reputation: 321

how to resend post multipart/form-data form with upload file to different server with node.js (express.js)?

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?

Upvotes: 17

Views: 7509

Answers (3)

bognix
bognix

Reputation: 43

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.

Upvotes: 0

IvanM
IvanM

Reputation: 3053

remove express.bodyParser and try pipes like these:

req.pipe(request('http://host/url/')).pipe(res)

Upvotes: 9

Carol Skelly
Carol Skelly

Reputation: 362670

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);
});

Upvotes: 7

Related Questions