max imax
max imax

Reputation: 2251

nodejs serve static file that is retrieved via external http request

i want to serve a static file to the client but the file will be retrieved via post request from another http server.

Im using nodejs and v0.10.24 and express v1.2.17

Im getting file using request module like this:

exports.command = function(req, res){
        request.post('http://127.0.0.1:8080/').form({filename:'gf', desc:'blaaaa'}, function (error, response, body) {
         //here i should return the file to the client.
        });
};

Upvotes: 0

Views: 136

Answers (2)

robertklep
robertklep

Reputation: 203329

Since request supports streams, this is an easy way to do what you want:

exports.command = function(req, res) {
  request
    .post('http://127.0.0.1:8080/')
    .form({ filename : 'gf', desc : 'blaaaa' })
    .pipe(res);
};

Advantage is that you don't need to read the entire file into memory first, but just stream the request response to the Express response.

Upvotes: 1

hexacyanide
hexacyanide

Reputation: 91659

Since the contents of the fetched page is contained in the body variable, just resend it off with your route handler. Here's an example with error handling:

exports.command = function(req, res){
  request.post(addr).form(opts, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      return res.send(body);
    }

    res.send(500);
  });
};

Upvotes: 1

Related Questions