NodeJS 下载卡住

问题描述 投票:0回答:1

我正在尝试使用 NodeJS 从我的 Apache 服务器下载 zip。当我尝试下载 zip 时,它下载了 8MB zip 中的大约 500KB,然后停止下载。 NodeJS 进程保持在线状态大约一分钟,然后因错误

read ETIMEDOUT
而终止。当我尝试使用浏览器通过同一端点下载相同的 zip 时,它会毫无问题地下载它。我尝试使用 NodeJS 脚本在多台服务器上下载 zip,排除了任何网络问题。我使用的NodeJS脚本如下:

const axios = require('axios').default;
const path = require('path');
const fs = require('fs');

axios.get('https://example.org/endpoint.php').then(res => {
    fs.writeFileSync(path.join(__dirname, `./file.zip`), res.data);
}).catch(console.log);

端点用 PHP 编写如下:

$zipPath = "/path/to/zip";

$filesize = filesize($zipPath);

header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="file.zip"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $filesize);

flush();

readfile($zipPath);
exit();

端点不会在响应中发送

Content-Length
标头,我不太明白。我在某处读到这可能会导致 NodeJS 脚本无法完全下载 zip,但我不太确定这是否正确。我尝试通过将标头名称更改为
$filesize
来检查是否是
X-Content-Length
变量导致问题,这给了我正确的输出,排除了该变量是原因。我还在某处读到标题
Transfer-Encoding: chunked
阻止我设置
Content-Length
标题。我尝试了几种对其他人有帮助的解决方案,但这些对我不起作用。这些是下载端点发送的标头:

HTTP/1.1 200 OK
Date: Wed, 24 Apr 2024 11:37:13 GMT
Server: Apache/2.4.52 (Ubuntu)
Content-Description: File Transfer
Content-Disposition: attachment; filename="file.zip"
Content-Transfer-Encoding: binary
Connection: Keep-Alive, Keep-Alive
Expires: 0
Cache-Control: must-revalidate, post-check=0, pre-check=0
Pragma: public
Upgrade: h2,h2c
Connection: Upgrade
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: application/zip

任何帮助将不胜感激。谢谢。

php node.js apache axios
1个回答
0
投票

您需要将响应通过管道传输到文件流中。

尝试以下:

const axios = require('axios').default;
const path = require('path');
const fs = require('fs');

axios.get('https://example.org/endpoint.php')
.then(res => {
    res.pipe(
        fs.openSync(path.join(__dirname, `./file.zip`)
          .createWriteStream()
    )
})
.catch(console.log);
© www.soinside.com 2019 - 2024. All rights reserved.