gpt4 book ai didi

node.js - 如何从 POST 请求中获取带有存档器的压缩文件?

转载 作者:太空宇宙 更新时间:2023-11-03 23:59:55 24 4
gpt4 key购买 nike

我正在使用 Express 构建一个 NodeJS API,当您进行 POST 时,它会根据正文生成一个 TAR 文件。请求。

Problem:

当端点是POST时,我可以访问请求的正文,并且似乎可以用它来做事情。但是,我无法从中查看/使用/测试压缩文件(据我所知)。

当端点是 GET 时,我无权访问请求正文(据我所知),但我可以在浏览器中查询 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 获取 TAR。 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() });
}
});

关于node.js - 如何从 POST 请求中获取带有存档器的压缩文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55292264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com