gpt4 book ai didi

node.js - 路由器级中间件 : undefined object

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

这是符合条件的:

someRouter.get('/...',
(req, res, next) => {
...
},
(req, res) => {...}

虽然这不符合条件:

someRouter.get('/...',
aMiddleware,
(req, res) => {...}

const aMiddleware = (req, res, next) => {...}

后者给出错误:

Error: Route.get() requires a callback function but got a [object Undefined]
at Route.(anonymous function) [as get] (/Users/Leon/Documents/Projects/NodeJS/DemoJWTinNodeJS/node_modules/express/lib/router/route.js:202:15)
at Function.proto.(anonymous function) [as get] (/Users/Leon/Documents/Projects/NodeJS/DemoJWTinNodeJS/node_modules/express/lib/router/index.js:510:19)
at Object.get (/Users/Leon/Documents/Projects/NodeJS/DemoJWTinNodeJS/src/routes/api/userRoute.js:30:12)
at Module._compile (internal/modules/cjs/loader.js:723:30)
at Module._compile (/Users/Leon/Documents/Projects/NodeJS/DemoJWTinNodeJS/node_modules/pirates/lib/index.js:99:24)
at Module._extensions..js (internal/modules/cjs/loader.js:734:10)
at Object.newLoader [as .js] (/Users/Leon/Documents/Projects/NodeJS/DemoJWTinNodeJS/node_modules/pirates/lib/index.js:104:7)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)

在我看来,它基本上提示 undefined object ,这应该是一个中间件。

中间件功能体完全相同。请问怎么了?

最佳答案

如果使用const关键字,请在router之前定义中间件,或者改为函数定义。

方法一:

const aMiddleware = (req, res, next) => {...}
someRouter.get('/...',
aMiddleware,
(req, res) => {...}

方法2:

someRouter.get('/...',
aMiddleware,
(req, res) => {...}
function aMiddleware(req, res, next){...}

关于node.js - 路由器级中间件 : undefined object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086716/

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