【发布时间】:2021-04-09 14:49:35
【问题描述】:
我从 Cypress 6.8.0 升级到 7.0.1。升级后,当 Cypress 测试之一调用此函数时
async saveTask (task, file) {
const requestBody = new FormData()
requestBody.append('file', file)
return await http.post('/api/endpoint', requestBody, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
},
我收到以下错误
TypeError [ERR_INVALID_ARG_TYPE] [ERR_INVALID_ARG_TYPE]:
The first argument must be of type string or an instance of Buffer or Uint8Array. Received type number (45)
at write_ (_http_outgoing.js:696:11)
at ClientRequest.write (_http_outgoing.js:661:15)
at Request.write (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:1496:27)
at /Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:546:20
at Array.forEach (<anonymous>:null:null)
at end (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:545:23)
at Immediate._onImmediate (/Users/donal/Library/Caches/Cypress/7.0.1/Cypress.app/Contents/Resources/app/packages/server/node_modules/@cypress/request/request.js:578:7)
at processImmediate (internal/timers.js:461:21)
{
code: 'ERR_INVALID_ARG_TYPE'
}
我用来发出 POST 请求的 http 对象是一个 Axios 实例,而我附加到请求正文的 file 对象是一个 File。文件对象是问题的原因,因为如果我不将其附加到请求正文中,则不会发生错误。
该错误仅在 Cypress 测试运行该函数时发生。 Cypress 使用 Node.js,从上面的错误消息来看,似乎不允许使用 File 类型。另外Axios request config docs表示Axios在Node下运行时,File是不允许的。
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
所以我想我需要将File 对象转换为其他东西,这样这个函数就可以在应用程序本身以及由赛普拉斯运行时工作。
在服务器端(Spring Boot 应用程序),此文件绑定到 MultipartFile
public void handlePost(
RequestPart(value = "file") MultipartFile file) {
// controller action body
}
如果我认为File 类型是问题所在,我应该改用什么以及如何进行转换?
【问题讨论】:
-
你可以把它放在你的表单中
<form role="form" id="sampleForm" action="/post/url" method="POST" enctype="multipart/form-data">
标签: javascript node.js axios cypress