【问题标题】:How to set Content-Type of Supertest attachment如何设置超测附件的Content-Type
【发布时间】:2019-06-15 02:33:56
【问题描述】:

我在我的应用程序中遇到了一个问题,如果文件是从 Microsoft Windows 发送的,则与上传文件相关联的 Content-Type 是错误的,给出 application/octet-stream,而如果从 Mac 发送则没问题,给出 text/csv .在将我的代码修复为不依赖请求中的 mime 类型之后,我想在我的一个测试中模拟这种情况。

鉴于以下请求,其中包括 JSON 字符串化的表单字段和文件附件,using supertest

  request(app)
    .post('/some/where')
    .field('someFormData', JSON.stringify(formData))
    .attach('someFile', 'someFile.csv')
    .expect(400)
    .end(done);

如何更改附件的Content-Type?查看 Edge 的 Network 选项卡,我希望看到上述请求的以下内容:

-----------------------------7e13121340602
Content-Disposition: form-data; name="someFormData"

{.............}
-----------------------------7e13121340602
Content-Disposition: form-data; name="someFile"; filename="someFile.csv"
Content-Type: application/octet-stream

ÿØÿà

(JSON 字符串已用点省略)

(我想模拟错误的内容类型,而不是显示text/csv。)

【问题讨论】:

    标签: node.js supertest


    【解决方案1】:

    使用 attach 的 contentType 选项对我有用:

    request(app)
        .post('/validateCertificate')
        .set('Content-type', 'multipart/form-data')
        .field('passphrase', '1234')
        .attach(
          'pfx',
          './src/build-request/test-certs/correct.pfx',
          { contentType: 'application/x-pkcs12' },
        )
        .expect(200))
    

    或者,如果您将缓冲区作为文件发送:

    request(app)
        .post('/validateCertificate')
        .set('Content-type', 'multipart/form-data')
        .field('passphrase', '1234')
        .attach(
          'pfx',
          buffer,
          { contentType: 'application/x-pkcs12', filename: 'correct.pfx' },
        )
        .expect(200))
    

    【讨论】:

    • 它对我不起作用,如果我删除{ contentType: 'application/x-pkcs12' },服务器会响应“请求中缺少文件”它可以工作(上传的文件没有我想要的内容类型)。所以我仍然无法设置我想要的内容类型
    • 设置filename 选项和contentType 选项对我有用。更新答案。
    【解决方案2】:
    request(app)
        .post('/some/where')
        .field('someFormData', JSON.stringify(formData))
        .set('Content-Type',  'application/octet-stream')
        .attach('someFile', 'someFile.csv')
        .expect(400)
        .end(done);
    

    【讨论】:

    • 嗨,这不起作用。我仍然得到原始内容类型。我的 req 对象(使用 Sails.js)在 req.headers 内部具有以下内容:'content-type': 'multipart/form-data; boundary=--------------------------709895074853423540687894'
    【解决方案3】:

    使用 .set() 设置您想要的任何 Content-Type。或任何类型的标题。

    【讨论】:

    • 您好,如果您有一个简单的请求,例如:.post('/wherever').set('Content-Type', 'application/octet-stream').send('hello');,则可以使用,但如果您使用 .field,它会变成 multipart/form-data
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 2014-03-06
    • 2020-09-30
    相关资源
    最近更新 更多