首页 > 解决方案 > 如何从 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数据?有没有办法“菊花链”请求(这似乎不干净,但也许是解决方案)?

标签: node.jsjsonexpressapi-designarchiverjs

解决方案


尝试这个:

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() });
  }
});

推荐阅读