如何在 Nodejs 中创建代理下载

2024-05-02

我想创建一个nodejs服务器,它充当下载文件的代理,即用户点击 在下载按钮上,从nodejs服务器调用get,nodejs服务器从不同的服务器获取链接 远程服务器并开始下载(以 TB 为单位)。然后将该下载转发给用户。 TB 文件不应存储在 Nodejs 服务器上然后发送。

这是我的尝试:

function (request, response) {

 // anything related to the remote server having the file
 var options= {
        path: "./bigData",
        hostname:"www.hugeFiles.net"
    }

    // get the file from the remote server hugefiles and push to user's response
    https.get(options, function(downFile)) {
        downFile.pipe(response) 
    }

}

在我使用之前res.download(file, function(err)) {}但文件必须从远程服务器完全下载


您非常接近,您发送了正确的 http 正文,但使用了错误的 http 标头。

这是一个最小的工作示例:

const express = require('express');
const http = require('http');

const app1 = express();

app1.get('/', function (req, res) {
  res.download('server.js');
});

app1.listen(8000);

const app2 = express();

app2.get('/', function (req, res) {
  http.get({ path: '/', hostname: 'localhost', port: 8000}, function (resp) {
    res.setHeader('content-disposition', resp.headers['content-disposition']);
    res.setHeader('Content-type', resp.headers['content-type']);
    resp.pipe(res);
  });
});

app2.listen(9000);

虽然我想说你应该看看像这样的模块https://github.com/nodejitsu/node-http-proxy https://github.com/nodejitsu/node-http-proxy负责处理标题等。 。 。为你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Nodejs 中创建代理下载 的相关文章

随机推荐