1

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

错误:

** Route.post() 需要一个回调函数,但得到了一个 [object Object]**

文件.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
  }

文件.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 })
}
4

1 回答 1

1

请仔细检查multer使用文档。

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

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

于 2019-07-21T19:03:51.990 回答