gpt4 book ai didi

node.js - 如何将中间件移至服务层

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:57 25 4
gpt4 key购买 nike

我尝试将中间件功能移至服务层,但运行时出现错误。我什至不确定我是否遵循了正确的分层。

错误:

** Route.post() requires a callback function but got a [object Object]**

file.service.ts

require('rootpath')()
const db = require('helpers/db.ts')
const mongoose = require('mongoose')
const multer = require('multer')
const GridFsStorage = require('multer-gridfs-storage')
const Grid = require('gridfs-stream')
const myCrypto = require('crypto')
const path = require('path')



var gfs = Grid(mongoose.connection, mongoose.mongo);
gfs.collection('uploads');


var storage = new GridFsStorage({
//url: mongoose.connection.client.s.url,
//options: options,
db: mongoose.connection,
file: (req, file) => {
return new Promise((resolve, reject) => {
myCrypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });

module.exports = {
upload
}

file.controller.ts

require('rootpath')()
const express = require('express')
const router = express.Router()
const fileService = require('routes/_shared/file.service.ts')

var logger = function(req, res, next)
{
console.log("File Controller");

next();
}

router.use(logger);
router.post('/upload', fileService.upload, fileUpload);

module.exports = router;

function fileUpload(req, res) {

res.send({ file: req.file })
}

最佳答案

请查看multer usage仔细记录。

您将 fileService.upload 作为第二个参数传递给 router.post 方法,并且 fileService.upload 是一个对象,而不是一个函数(错误消息指出)。

相反,您应该传递 fileService.upload.single('avatar') 或使用其他 upload 方法,例如 arrayfieldsanynone

关于node.js - 如何将中间件移至服务层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com