Node/Express导出多个中间件报错:Route.get()需回调函数而非对象
问题原因与解决办法
错误根源
你遇到的Error: Route.get() requires a callback function but got a [object Object],本质是导出多个中间件后,路由代码里错误地传入了整个导出对象而非单个中间件函数。
- 当你用
module.exports = isAuth导出单个函数时,const MW = require('./middleware')拿到的是isAuth函数本身,此时router.get('/check', MW, ...)是合法的; - 改成导出对象
{ isAuth, otherMiddleware }后,MW变成了包含两个函数的对象,如果你仍直接把MW作为中间件参数传入router.get(),Express就会收到一个对象而非回调函数,触发报错。
你误以为是加入MW.otherMiddleware导致的问题,实际是添加该中间件时可能误写了参数(比如把MW.otherMiddleware写成了MW),或是之前的路由代码就错误使用了整个MW对象。
正确用法
方式1:通过对象属性引用中间件
// 导入中间件对象 const MW = require('./path/to/your/middleware-file') // 正确传入单个中间件函数,多个中间件依次排列 router.get('/check', MW.isAuth, MW.otherMiddleware, function (req, res) { res.send({ message: 'Auth passed' }) })
方式2:解构导入单个中间件
// 直接解构导出的函数 const { isAuth, otherMiddleware } = require('./path/to/your/middleware-file') // 直接使用函数作为中间件 router.get('/check', isAuth, otherMiddleware, function (req, res) { res.send({ message: 'Auth passed' }) })
总结
只要确保传入router.get()的每一个中间件/回调都是函数类型,而非导出的整个对象,就能解决这个报错。
内容的提问来源于stack exchange,提问作者mikeym
相关产品推荐
相关产品推荐

