如何在nodejs控制器中添加中间件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (84)

我有一个如下所示的router.js:

'use strict';

const express = require('express');
const router = express.Router();

const signupController = require('../controller/signup.controller');
const signinController = require('../controller/signin.controller');
const userListController = require('../controller/userList.controller');
const productController = require('../controller/product.controller');

const passport = require('passport');
require('../config/passport')(passport);


router.get('/users', passport.authenticate('jwt', {session: false}), userListController.getUserList);

router.post('/product', productController.addProduct)

router.post('/user/signup', signupController.Signup);

router.post('/user/signin', signinController.Signin);


module.exports = router;

并在productController.addProduct我有这样的代码:

'use strict';
var mongoose = require('mongoose');
var Product = require('../model/product.model');
var multer = require('multer');
var path = require('path');


// File storage configuration
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, '...store some where in filesystem...');
    }
});

// File filter configuration
const fileFilter = (req, file, cb) => {
    if (path.extname(file) === '.gpg') {
        cb(null, true);
    } else {
        cb(null, false);
    }
};

// File upload configuration
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 5
    },
    //fileFilter: fileFilter
});


// Loader module
exports.addProduct = (req, res, next) => {
    console.log(req.file);
    ...    
} 

如何将上传添加到exports.addProduct =(req,res,next)=> {},这样我就可以访问req.file

我试过这样的事情,但没有奏效:

exports.addProduct =(upload.single('productImage'),(req,res,next)=> {}

提问于
用户回答回答于

我会试试这个:

productController出口你的upload。所以你需要添加:

exports.upload = upload;

// Loader module
exports.addProduct = ... // like in your code

由于路由器功能期望所有回调,请修改你的router.js

router.post('/product', productController.upload, productController.addProduct);

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励