Search code examples
node.jsnode-request

pipe image request coming from frontend in nodejs with custom headers


I need to pipe the image request coming from frontend to another url in nodejs with custom headers. I have a code which already works for the same without headers.

html:

<form id="ImageForm" method="post" enctype="multipart/form-data" action="/image/test" name="image-test-form">
  <input type="file" accept="image/*" />
  <input type="submit" />
</form>

Using express and request (this code works fine) :

app.post( '/image/test', (req, res, next) => {
  var url = "http://www.somedomain.com/image/test";
  var headers = {'h1': 'test', 'h2': 'header'}; // TODO: send headers
  req.pipe(request.post (url,req.body)).pipe(res)
  .on('error', function(err) { res.status(500).send(err);});
});

I couldn't figure out how to pass headers along the request. Tried to use formData and form in request, not working.


Solution

  • Before piping, you can add your custom headers to req.headers:

    req.headers.h1 = 'test';
    req.headers.h2 = 'header';
    
    req.pipe(request.post (url,req.body)).pipe(res)