NodeJS / Express: what is “app.use”?

后端 未结 23 1424
别跟我提以往
别跟我提以往 2020-11-29 14:48

In the docs for the NodeJS express module, the example code has app.use(...).

What is the use function and where is it defined?

23条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 15:25

    app.use(path, middleware) is used to call middleware function that needs to be called before the route is hit for the corresponding path. Multiple middleware functions can be invoked via an app.use.

    app.use(‘/fetch’, enforceAuthentication) -> enforceAuthentication middleware fn will be called when a request starting with ‘/fetch’ is received. It can be /fetch/users, /fetch/ids/{id}, etc

    Some middleware functions might have to be called irrespective of the request. For such cases, a path is not specified, and since the the path defaults to / and every request starts with /, this middleware function will be called for all requests.

    app.use(() => { // Initialize a common service })

    next() fn needs to be called within each middleware function when multiple middleware functions are passed to app.use, else the next middleware function won’t be called.

    reference : http://expressjs.com/en/api.html#app.use

    Note: The documentation says we can bypass middleware functions following the current one by calling next('route') within the current middleware function, but this technique didn't work for me within app.use but did work with app.METHOD like below. So, fn1 and fn2 were called but not fn3.

    app.get('/fetch', function fn1(req, res, next)  {
        console.log("First middleware function called"); 
            next();
        }, 
        function fn2(req, res, next) {
            console.log("Second middleware function called"); 
            next("route");
        }, 
        function fn3(req, res, next) {
            console.log("Third middleware function will not be called"); 
            next();
        })
    

提交回复
热议问题