node.js - 如何从 POST 请求中获取带有存档器的压缩文件?
问题描述
我正在NodeJS API
使用 Express 构建一个,当您创建一个时,它会根据请求的正文POST
生成一个文件。TAR
问题:
当端点是 aPOST
时,我可以访问请求的主体,并且似乎可以用它来做事。但是,我看不到/使用/测试压缩文件(据我所知)。
当端点是 aGET
时,我无法访问请求的正文(据我所知),但我可以在浏览器中查询 URL 并获取压缩文件。
基本上我想解决“据我所知”之一。到目前为止,这是我的相关代码:
const fs = require('fs');
const serverless = require('serverless-http');
const archiver = require('archiver');
const express = require('express');
const app = express();
const util = require('util');
app.use(express.json());
app.post('/', function(req, res) {
var filename = 'export.tar';
var output = fs.createWriteStream('/tmp/' + filename);
output.on('close', function() {
res.download('/tmp/' + filename, filename);
});
var archive = archiver('tar');
archive.pipe(output);
// This part does not work when this is a GET request.
// The log works perfectly in a POST request, but I can't get the TAR file from the command line.
res.req.body.files.forEach(file => {
archive.append(file.content, { name: file.name });
console.log(`Appending ${file.name} file: ${JSON.stringify(file, null, 2)}`);
});
// This part is dummy data that works with a GET request when I go to the URL in the browser
archive.append(
"<h1>Hello, World!</h1>",
{ name: 'index.html' }
);
archive.finalize();
});
我发送给此的示例 JSON 正文数据:
{
"title": "Sample Title",
"files": [
{
"name": "index.html",
"content": "<p>Hello, World!</p>"
},
{
"name": "README.md",
"content": "# Hello, World!"
}
]
}
我只是应该发送JSON
并获取一个基于SON
. 这POST
是错误的方法吗?如果我使用GET
,应该更改什么以便我可以使用该JSON
数据?有没有办法“菊花链”请求(这似乎不干净,但也许是解决方案)?
解决方案
尝试这个:
app.post('/', (req, res) => {
const filename = 'export.tar';
const archive = archiver('tar', {});
archive.on('warning', (err) => {
console.log(`WARN -> ${err}`);
});
archive.on('error', (err) => {
console.log(`ERROR -> ${err}`);
});
const files = req.body.files || [];
for (const file of files) {
archive.append(file.content, { name: file.name });
console.log(`Appending ${file.name} file: ${JSON.stringify(file, null, 2)}`);
}
try {
if (files.length > 0) {
archive.pipe(res);
archive.finalize();
return res.attachment(filename);
} else {
return res.send({ error: 'No files to be downloaded' });
}
} catch (e) {
return res.send({ error: e.toString() });
}
});
推荐阅读
- python - 从朱利安字符串中获取日期和时间
- android - WebView 使用 GET 缓存进行 PUT
- python - 试图更改副本但更改原件:(
- javascript - 服务工作者“内容下载”可以比实际获取时间长吗?
- javascript - webpack:即使在断点上,也可以实时重新加载强制 chrome 重新加载
- docker - 如何使用 WLST 启用 WebLogic 摘要身份验证
- ios - iOS 无法将图像上传到移动数据/4G 网络上的服务器,而在 Wifi 中它工作正常
- python - 我对 Python 的 for in 循环有疑问
- android - 从 App Widget 管理点击按钮
- python - text3D 上升或下降与相同的 zdir matplotlib python 绘图图