【问题标题】:How to put a PDF with chai-http?如何使用 chai-http 放置 PDF?
【发布时间】:2026-01-11 08:25:06
【问题描述】:

好的,这是一个非常全面的问题,因为我需要了解流程和最佳实践。欢迎批评!

我正在为PDF-to-image API 端点编写测试。因此,我需要将 PDF put 发送到 endpoint。端点会将其保存在本地,进行转换,将图像序列存储在 S3 存储桶中,然后发回 URL 数组。但是,由于我编写这个测试主要是为了帮助开发,所以还没有发生。我只是想确保我可以在端点接收 PDF 并保存它。

查看下面的测试代码:

// testing dependencies
const chai = require("chai")
const chaiHttp = require("chai-http")
const should = chai.should()
const server = require('./../index.js')

chai.use(chaiHttp)

// utility dependencies
const fs = require('fs')

describe("PDF upload", () => {
  it("should PUT my pdf", (done) => {
    fs.readFile('./content/pdf/lockheed.pdf', (err, res) => {
      if (err) { console.error(err) }
      else {
        chai.request(server)
          .put('/v1/convert-pdf')
          .set('Content-Type', 'application/pdf')
          .send({ pdf: res })
          .end((err, res) => {
            console.log("got the res")
            if (err) { console.error(err) }
            else { console.log(res.body) }

            done()
          })
      }
    })
  })
})

在设置 Content-Type 标头之前,我会从服务器获取 413(请求太大)。我已经将所有超时和最大请求​​大小设置得非常大,所以这真的不应该成为问题。但是现在我在标题中有application/pdf,我收到了这个错误:

Uncaught TypeError: "string" must be a string, Buffer, or ArrayBuffer

这更有帮助,并引导我找到SO,它将文件通过管道传输到请求。但是,我真的不确定如何通过chai-http 完成此操作,以便我的服务器可以成功获取 pdf 并将其保存到本地文件。

【问题讨论】:

    标签: javascript node.js http testing chai


    【解决方案1】:

    要通过chai-http 上传文件,请使用attach 而不是send。这是一个例子:

    describe("PDF upload", () => {
      it("should PUT my pdf", (done) => {
        chai.request(server)
          .put('/v1/convert-pdf')
          .set('Content-Type', 'application/pdf')
          .attach('fileField', './content/pdf/lockheed.pdf', 'lockheed.pdf')
          .end((err, res) => {
            console.log("got the res");
            if (err) {
              console.error(err)
            } else {
              console.log('success');
              console.log(res.body)
            }
            done();
          });
      })
    })
    

    实际上,chai-http 遵循与SuperAgent 相同的 API。详情请查看document

    【讨论】:

    • 有趣啊!当我有机会时,我将不得不试一试。实际上,我最终将它附加为来自 fs.readFile 的缓冲区,这完成了工作,但我很乐意尝试更简洁的解决方案
    • @Corbfon 您的问题得到了正确回答吗?如果是,也许您可​​以“接受”这个答案?