我发出发布请求时遇到意外的字段错误?这是我的节点js代码
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var PORT = process.env.PORT || 3000;
var upload = multer({ dest: 'uploads/' })
// use of body parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(cors());
app.post('/upload',upload.single('avatar'), function (req, res,next) {
console.log(req.file);
console.log('hello');
res.send({data:'sss'})
});
app.listen(PORT, () => {
console.log(`App is listening to ${PORT}`);
})
我正在使用此插件上传文件https://www.npmjs.com/package/multer
当我通过postman
访问服务时,我遇到了错误
**App is listening to 3000
Error: Unexpected field
at makeError (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\multer\lib\make-error.js:12:13)
at wrappedFileFilter (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\multer\index.js:40:19)
at Busboy.<anonymous> (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\multer\lib\make-middleware.js:114:7)
at emitMany (events.js:147:13)
at Busboy.emit (events.js:224:7)
at Busboy.emit (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\busboy\lib\main.js:38:33)
at PartStream.<anonymous> (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\busboy\lib\types\multipart.js:213:13)
at emitOne (events.js:116:13)
at PartStream.emit (events.js:211:7)
at HeaderParser.<anonymous> (C:\Users\B0207296\WebstormProjects\uploadFile\node_modules\dicer\lib\Dicer.js:51:16)**
邮递员图片
答案 0 :(得分:1)
在PostMan中,将密钥重命名为avatar
编辑:
multer
期望上载文件的name
是avatar
,而不是file_test
答案 1 :(得分:0)
我的问题是 roter
文件中的一个错误。
我有:
router.post(
"/addArticle",
upload.single("image"),
upload.array("rowPics"),
(req, res, next)=>{...some code}
)
我的目标是上传一个名为 image
的文件和多个文件作为一个名为 rowPics
的数组。但不能同时使用 upload.single
和 upload.array
。为了上传具有不同名称的多个文件,我不得不像下面这样更改我的代码:
router.post(
"/addArticle",
upload.fields([
{name: "image", maxCount: 1},
{name: "rowPics"}
]),
(req, res, next)=>{...some code}
)
在 ...some code
部分,我解析了如下输入:
let image = req.files.image[0].path
let rowPics = req.files.rowPics.map(el=>el.path)
问题解决了。