节点(快速)中间件-如何正确地绑定到不同的端点

时间:2018-09-03 15:42:41

标签: node.js express middleware endpoint

我开始涉猎Express,他们具有中间件的这一功能,此刻我正在探索。

因此,假设我有2个端点(/middlewaredemoa/middlewaredemob),它们都需要一些不同的初始处理。然后他们有一个通用的中间件,无论最初的终点如何,都适用于相同的处理方式。

我不确定在使用GET()提供响应时执行的操作是否正确。在我看来,如果我有2个不同的终结点,则它们各自需要自己的app.get("/middlewaredemoa", ...)。一定是这样吗?假设我只是对变量进行某种处理,然后我需要以它最终处于的任何状态返回该var,我仍然最好为每个端点定义1个get()吗?

let response = ""
app.use('/middlewaredemoa', (req, resp, next) => {
    response = "Greetings from: M1a"

    if ( Math.floor((Math.random() * 10) + 1) >=4){
        console.log("M1a gets req and passes it on to two")
        next()
    } else {
        throw "ARRRRRRRRRRRRRGGGGHHHHHH!"
    }
})

app.use('/middlewaredemob', (req, resp, next) => {
    response = "Greetings from: M1b"

    if ( Math.floor((Math.random() * 10) + 1) >=4){
        console.log("M1b gets req and passes it on to two")
        next()
    } else {
        throw "ARRRRRRRRRRRRRGGGGHHHHHH!"
    }
})

//some common treatment for all the above endpoints
app.use((req, resp, next) => {
    response += " and M2"

    if ( Math.floor((Math.random() * 10) + 1) >=4){
        console.log("M2 gets req and passes it on to GET()")
        next()
    } else {
        throw "ARRRRRRRRRRRRRGGGGHHHHHH!"
    }
})

//get - need 1 get per endpoint?
app.get("/middlewaredemoa",(req,resp) => {
    console.log("GET() handler after the middlewares")
    resp.send(response + " and GET() 1")
})
app.get("/middlewaredemob",(req,resp) => {
    console.log("GET() handler after the middlewares")
    resp.send(response + " and GET() 2")
})

/*ERROR HANDLING - could use same pattern as above to chain errors*/

app.use((err, req, resp, next) => {
    console.log("CRASH BOOM UH!:"+err)
    resp.status(500).send("Poop hit the fan HARD")
})

1 个答案:

答案 0 :(得分:1)

Express提供了一种使用数组来匹配多个路由的方法。

赞:

req.get(['/routea', '/routeb'], (req, res, next) => {
 // do something
 // res.send() if you want to send a response right away
 // next() if you want to go to the next middleware
});

req.get只是类似于req.use的中间件,只匹配req.method === 'GET'

编辑:对于注释中的奖励问题。 它只是一个中间件。使用与普通中间件相同的缩放技术。