You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中复现带二进制文件的Postman API请求?

在Cypress中复现带二进制文件的Postman PUT请求

根据你提供的Postman请求场景和当前Cypress代码的问题,以下是针对性的修复方案:

方案1:直接发送二进制数据(匹配Postman Raw二进制模式)

如果你的Postman请求是直接将二进制文件内容作为请求体发送(而非通过form-data表单),需要去掉form: true配置,并正确设置请求头和编码:

cy.fixture(objData.fixtureFilePath, 'binary').then((file) => {
  cy.request({
    method: 'PUT',
    url: url,
    headers: {
      // 替换为Postman中实际使用的Content-Type,比如application/octet-stream、image/png等
      'Content-Type': 'application/octet-stream'
    },
    body: file,
    encoding: 'binary' // 确保文件以二进制编码发送
  }).then((response) => {
    expect(response.status).to.eq(200)
  })
})

方案2:通过form-data表单发送文件(匹配Postman FormData模式)

如果Postman是通过form-data字段上传文件,需要构造FormData对象作为请求体,而非直接传入文件内容:

cy.fixture(objData.fixtureFilePath, 'binary').then((file) => {
  const formData = new FormData()
  // 替换为Postman中对应的字段名和文件名
  formData.append('file', file, 'your-file-name.png')

  cy.request({
    method: 'PUT',
    url: url,
    body: formData,
    // 无需手动设置Content-Type,Cypress会自动添加正确的multipart/form-data及边界值
    headers: {
      // 若接口需要其他认证头(如Token),请在此补充
      // 'Authorization': 'Bearer your-token'
    }
  }).then((response) => {
    expect(response.status).to.eq(200)
  })
})

关键调试步骤

  • 对比Postman和Cypress的请求头:打开Postman的「请求详情」,查看所有请求头(如Authorization、Content-Type等),确保Cypress请求中包含相同的头信息。
  • 导出Postman请求的cURL命令,与Cypress发送的请求进行对比,排查请求体、编码或头信息的差异。

内容的提问来源于stack exchange,提问作者J.Cruz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:42:32