我想调整图片大小。为此我使用nodejs和sharp模块。但是我收到一个错误,说明帖子需要回调函数而不是对象。以下是我的代码。
router.post('/uploadAvatar',
multer({
dest: './public/uploads/images/avatars',
rename: function (fieldname, filename) {
return 'avatar'+Date.now();
}
}), function(req, res) {
// resize image
sharp(newPath).resize(300, 200).toFile(newPath, function(err) {
if (err) {
throw err;
}
res.json(newPath);
});
});
我收到以下错误 -
/home/chyangba/Desktop/sharptest/sharpApp/node_modules/express/lib
/router/route.js:196
throw new Error(msg);
^
Error: Route.post() requires callback functions but got a [object Object]
at Route.(anonymous function) [as post] (/home/chyangba/Desktop/sharptest/sharpApp/node_modules/express/lib/router/route.js:196:15)
at Function.proto.(anonymous function) [as post] (/home/manoj/Desktop/sharptest/sharpApp/node_modules/express/lib/router/index.js:510:19)
at Object.<anonymous> (/home/chyangba/Desktop/sharptest/sharpApp/routes/index.js:31:13)
答案 0 :(得分:0)
您使用的是multer错误,multer({})返回的是一个对象而不是中间件。
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
如你所见,你必须在multer对象上调用 single,array,... 来获取中间件!