Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

node.js - before and after hooks for a request in express (to be executed before any req and after any res)

ExpressJS middleware req, res, next have hooks like .on and .pipe.

But I'm looking for hooks for the app.get and app.post methods.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

app.use() and middleware can be used for "before" and a combination of the 'close' and 'finish' events can be used for "after."

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterResponse);
        res.removeListener('close', afterResponse);

        // action after response
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // action before request
    // eventually calling `next()`
});

app.use(app.router);

An example of this is the logger middleware, which will append to the log after the response by default.

Just make sure this "middleware" is used before app.router as order does matter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...