express(使用multer)错误:Multipart:找不到边界,POSTMAN发送请求

9 forms node.js express multer

注意:只有当我在Postman中使用form-data body表单时(由于我想在文本字段旁边发送文件,我必须使用该表单),我得到:

Error: Multipart: Boundary not found.

当我使用x-www-form-urlencoded时一切正常.(当使用body-parser作为中间件时)

这是请求内容:(由邮递员制作)

POST /test HTTP/1.1
Host: localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Cache-Control: no-cache
Postman-Token: 61089a44-0b87-0530-ca03-a24374786bd1

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="test"

a simple word
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="data"

good
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Run Code Online (Sandbox Code Playgroud)

index.js:

var express = require('express');
var app = express();

var multer = require('multer');
var upload = multer();

app.post('/test', upload.array(), function (req, res, next) {
    console.log(req.body.test);
    console.log(req.body);
});

app.listen(3000, function () {
    console.log('app started');
});
Run Code Online (Sandbox Code Playgroud)

提前致谢.

小智 25

我找到了解决方案.我只需要阻止Postman发送Content-Type标题.所以我只是从请求标题中删除它.

也许它有助于某人.

  • 谢谢你,它有效。您能解释一下这背后的原因吗? (3认同)

Leo*_*one 11

为了深入了解为什么会发生这种情况,

在任何 HTTP 请求中使用内容类型时multipart/form-data,您可以在规范旁边添加边界信息,Content-Type例如:

Content-Type: multipart/form-data; boundary=MyBoundary
Run Code Online (Sandbox Code Playgroud)

您可以替换MyBoundary为您喜欢的任何字符串。

然后您必须将表单数据 ( name=Abebe&age=5) 编码为:

--MyBoundary
Content-Disposition: form-data; name="name"

Abebe
--MyBoundary
Content-Disposition: form-data; name="age"

5
--MyBoundary--
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请阅读此 StackOverflow 问题和答案


小智 10

如果您使用 fetch 方法

fetch("http://localhost:4000/upload_files", {
    method: 'POST',
    body: formData,
    headers: {
      "Content-Type": "multipart/form-data"
    }
})
Run Code Online (Sandbox Code Playgroud)

headers 以便 Fetch api 自动设置 headers。现在删除标题或“Content-Type”:“multipart/form-data”

fetch("http://localhost:4000/upload_files", {
    method: 'POST',
    body: formData
})
Run Code Online (Sandbox Code Playgroud)

现在可以了


小智 5

对于JMeter和postmanContent-Type从header中删除。

它会解决你的问题。