我正在嘗試獲取特定請求路由中的中間件函式的名稱。假設我實作了以下代碼:
const authorizeRoute = (req,res,next) => {
let nextFunctionName = SomeFunctionToRetrieveTheNameOfTheNextMiddlewareToBeCalled()
if (isUserAuthorized(req.user.id, nextFunctionName)) next()
}
app.use(authorizeRoute)
app.get("/users", controller.getUsers)
app.get("/users/:id/posts", controller.getUserPosts)
我希望authorizeRoute中間件能夠獲取堆疊中下一個要呼叫的中間件函式的名稱。
就像,如果有對 的GET請求"/users",我希望nextFunctionName具有"getUsers"或 “controller.getUsers” 或類似的值。或者GET "/users/:id/posts"具有相同的nextFunctionName是"getUserPosts"什么。
我將如何做到這一點?
我還是 Express 和 Node 甚至 javascript 的新手。我該怎么做呢?
我知道這是可能的,因為已經有一種方法可以在 javascript 中將函式名稱作為字串獲取。
someFunction.name // gives "someFunction" returned as a string
所以我知道這是可以做到的。我只是不知道,如何。
PS 我知道有其他方法可以實作所需的效果,但是我對此的需求并未完全反映在上面的代碼段中,但我已盡力將其展示出來。
uj5u.com熱心網友回復:
弄清楚了。我不能放置中間件來獲取使用的路由的堆疊,app.use但是如果將中間件放在路由的處理程式中,它將起作用。
const SomeFunctionToRetrieveTheNameOfTheLastMiddleware(req) => {
let stack = req.route.stack
return stack[stack.length-1].name
}
const authorizeRoute = (req,res,next) => {
let nextFunctionName = SomeFunctionToRetrieveTheNameOfTheLastMiddleware(req)
if (isUserAuthorized(req.user.id, nextFunctionName)) next()
}
app.get("/users", authorizeRoute, controller.getUsers)
app.get("/users/:id/posts", authorizeRoute, controller.getUserPosts)
我在問題本身就有了問題的答案??
uj5u.com熱心網友回復:
你不想做一些動態的事情,保持簡單。為什么不這樣做:
const nextFunctionName = (user)=>{
// blah blah blah (something synchronous not asynchronous)
}
const authorizeRoute = (req,res,next) => {
if (isUserAuthorized(req.user?.id)){
nextFunctionName(req.user)
}
next()
}
但看起來你實際上只是想這樣做:
const nextFunctionName = (user, next)=>{
// blah blah blah
next();
}
const authorizeRoute = (user, next) => {
if (isUserAuthorized(user.id)){
nextFunctionName(user, next); // pass in the next callback
} else {
next()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350170.html
標籤:javascript 表达 中间件
