我设置了这样的multer
let multer = require('multer');
let apiRoutes = express.Router();
let UPLOAD_PATH = '../uploads';
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, UPLOAD_PATH);
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now());
}
});
let upload = multer({ storage: storage });
在路线中,我正在获取数据和图像,并使用multer!
apiRoutes.post('/update', passport.authenticate('jwt', { session: false }), (request, response) => {
let record = {
name: request.body.name,
location: request.body.location,
about: request.body.about,
userid: request.body.userid,
avatar: request.body.filename
};
let userData = {
name: request.body.name
};
if (request.body.filename) {
upload(request, response, (error) => {
});
}
profile.findOneAndUpdate({ userid: request.body.userid }, record, {new: true}, (error, doc) => {
if (error) response.json(error);
user.findOneAndUpdate({ _id: request.body.userid }, record, (error, result) => {
if (error) throw error;
response.json(doc);
});
});
});
这段代码发生的事情是,当我不向后端发送图像时,我从前端获取数据并将其存储到数据库中。但是当我沿着侧面数据发送图像时,它会返回POST /api/1.0/profile/update 401 0.396 ms - -
。
这意味着我根本没有得到任何数据。什么在这里用代码拧干?
答案 0 :(得分:0)
您无法在/ update路线中使用Multer。像你一样在你的路由器中使用Multer:
var upload = multer({ dest: 'uploads/' })
apiRoutes.post('/profile', upload.single('image'), function (req, res, next) {
// Uploaaded
})
如果您添加它但仍然无法获取我们的文件,则应使用以下参数更新您的表单:enctype="multipart/form-data"