使用Postman表达后端的HTTP请求抛出了意外的表单结束(多部分表单数据)



我正在发送一个多部分/表单数据请求到我的api后端(在谷歌功能)使用邮差。在请求中,我发送了两个字段和一个文件。请求由Multer/busboy处理,这会抛出错误-表单的意外结束。以下是我对邮差的原始请求:

POST /app/api/projects/newproject HTTP/1.1
Content-Type: multipart/form-data; boundary=XXX
User-Agent: PostmanRuntime/7.29.0
Accept: */*
Postman-Token: a339b8c1-caa3-4629-8adf-d20967f84
Host: my-projectxxx.cloudfunctions.net
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: connect.sid=s%3A3h93yTISWRf4cibUG-8Ra3HpqV_iznVz.GhVvgAynx1RuwTyzjCCAlb%2FspGgTzf%2F%2F6VJrkGvNJ
Content-Length: 718115

--XXX
Content-Disposition: form-data; name="file"; filename="aliens.png"
Content-Type: image/png
<aliens.png>
--XXX
Content-Disposition: form-data; name="name"
Content-Type: text
John
--XXX
Content-Disposition: form-data; name="is_photo_changed"
Content-Type: text
1
--XXX--

HTTP/1.1 500 Internal Server Error
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
content-security-policy: default-src 'none'

下面是我的api后端日志中记录的错误:

Unexpected end of form at Multipart._final (/workspace/node_modules/busboy/lib/types/multipart.js:588:17) at callFinal (node:internal/streams/writable:694:27) at prefinish (node:internal/streams/writable:723:7) at finishMaybe (node:internal/streams/writable:733:5) at Multipart.Writable.end (node:internal/streams/writable:631:5) at onend (node:internal/streams/readable:693:10) at processTicksAndRejections (node:internal/process/task_queues:78:11)

它可以在本地运行,但在部署并在google云功能中使用后抛出错误。这个请求有什么问题吗?有其他的邮递员来测试吗?

在我的例子中,这是由于在控制器功能之前使用了多点上传功能。将上传功能放在控制器功能之后解决了此错误。

router.post(
"/",
validateAccessToken,
validateAdminRole,
validateCreateBlogSchema,
blogController.create,
upload.single("image")
);

标题和内容之间必须有空行,例如:

--XXX
Content-Disposition: form-data; name="name"
Content-Type: text
John
--XXX

多部分请求正文中的行必须以CRLF结尾,而不仅仅是LF。

下面的代码演示了这一点:
express().post("/", multer().fields([]), function(req, res) {
res.json(req.body);
})
.listen(80, function() {
http.request("http://localhost", {
method: "POST",
headers: {"Content-Type": "multipart/form-data;boundary=XXX"}
}).end(`--XXX
Content-Disposition: form-data; name="name"
Content-Type: text
John
--XXX--`.replace(/n/g,"rn"))
.on("response", function(r) {
r.pipe(process.stdout);
});
});

删除John前的空行或删除.replace会导致&;Unexpected end of form&;multer.

相关内容

  • 没有找到相关文章

最新更新