简体   繁体   English

nodejs提供通过外部http请求检索的静态文件

[英]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. 我想向客户端提供静态文件,但该文件将通过另一个http服务器的post请求检索。

Im using nodejs and v0.10.24 and express v1.2.17 我使用nodejs和v0.10.24并表达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.
        });
};

Since the contents of the fetched page is contained in the body variable, just resend it off with your route handler. 由于获取页面的内容包含在body变量中,因此只需使用路径处理程序重新发送它。 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);
  });
};

Since request supports streams, this is an easy way to do what you want: 由于request支持流,因此这是一种简单的方法来执行您想要的操作:

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. 优点是您不需要首先将整个文件读入内存,而只需将request响应流式传输到Express响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM