Javascript 上载包含文档的多个文件
我想添加多个文件和文件,它的工作,但我有多个错误,所有的东西都可以看到后重新加载页面。 以下是我的邮寄路线:Javascript 上载包含文档的多个文件,javascript,post,mongoose,response,multer,Javascript,Post,Mongoose,Response,Multer,我想添加多个文件和文件,它的工作,但我有多个错误,所有的东西都可以看到后重新加载页面。 以下是我的邮寄路线: // @route POST /upload // @desc Uploads file and object to DB router.post('/', upload.any(), (req, res) => { if (req.files !== undefined) { console.log(req.files); req.files.map(({
// @route POST /upload
// @desc Uploads file and object to DB
router.post('/', upload.any(), (req, res) => {
if (req.files !== undefined) {
console.log(req.files);
req.files.map(({ id, filename }) => {
const newGallery = new Gallery({
files_id: id,
image: '/api/gallery/image/' + filename,
description: req.body.description,
tripLocation: req.body.tripLocation,
})
newGallery.save().then(photo => res.json(photo))
});
}
});
下面是警告/错误(如果我上传X个文件,我会收到X个错误,并且这个拒绝id:X是文件的订单号):
(节点:7855)未处理的PromisejectionWarning:错误
[ERR_HTTP_HEADERS_SENT]:无法在将头发送到服务器后设置头
ServerResponse.setHeader上的客户端[0](_http_outgoing.js:470:11)
ServerResponse.header上的[0]
(/home/wiktor/MyApp/node_modules/express/lib/response.js:771:10)
[0]位于ServerResponse.send
(/home/wiktor/MyApp/node_modules/express/lib/response.js:170:12)
[0]位于ServerResponse.json
(/home/wiktor/MyApp/node_modules/express/lib/response.js:267:15)
[0]位于newGallery.save.then.photo
(/home/wiktor/MyApp/routes/api/gallery.js:94:43)[0]
进程。_tick回调(内部/process/next_tick.js:68:7)[0]
(节点:7855)未处理的PromisejectionWarning:未处理的承诺
拒绝。此错误源于在异步
函数没有catch块,或者拒绝了
未使用.catch()处理。(拒绝id:6)
我怀疑这个问题可能与res.json()有关,我所研究的res.json()应该只使用一次。您可以这样尝试:
// @route POST /upload
// @desc Uploads file and object to DB
router.post('/', upload.any(), async (req, res, next) => {
if (req.files !== undefined) {
console.log(req.files);
await Promise.all(req.files.map(({ id, filename }) => {
const newGallery = new Gallery({
files_id: id,
image: '/api/gallery/image/' + filename,
description: req.body.description,
tripLocation: req.body.tripLocation,
})
return newGallery.save()
})).then(data => res.json(data))
.catch(err => next(err))
}
});