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

后端 未结 23 1106
别跟我提以往
别跟我提以往 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:24

    app.use() works like that:

    1. Request event trigered on node http server instance.
    2. express does some of its inner manipulation with req object.
    3. This is when express starts doing things you specified with app.use

    which very simple.

    And only then express will do the rest of the stuff like routing.

    0 讨论(0)
  • 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();
        })
    
    0 讨论(0)
  • 2020-11-29 15:26

    app.use
    is created by express(nodejs middleware framework )
    app.use is use to execute any specific query at intilization process
    server.js(node)
    var app = require('express');
    app.use(bodyparser.json())
    so the basically app.use function called every time when server up

    0 讨论(0)
  • 2020-11-29 15:27

    app.use() used to Mounts the middleware function or mount to a specified path,the middleware function is executed when the base path matches.

    For example: if you are using app.use() in indexRouter.js , like this:

    //indexRouter.js
    
    var adsRouter = require('./adsRouter.js');
    
    module.exports = function(app) {
        app.use('/ads', adsRouter);
    }
    

    In the above code app.use() mount the path on '/ads' to adsRouter.js.

    Now in adsRouter.js

    // adsRouter.js
    
    var router = require('express').Router();
    var controllerIndex = require('../controller/index');
    router.post('/show', controllerIndex.ads.showAd);
    module.exports = router;
    

    in adsRouter.js, the path will be like this for ads- '/ads/show', and then it will work according to controllerIndex.ads.showAd().

    app.use([path],callback,[callback]) : we can add a callback on the same.

    app.use('/test', function(req, res, next) {
    
      // write your callback code here.
    
        });
    
    0 讨论(0)
  • 2020-11-29 15:28

    app.use applies the specified middleware to the main app middleware stack. When attaching middleware to the main app stack, the order of attachment matters; if you attach middleware A before middleware B, middleware A will always execute first. You can specify a path for which a particular middleware is applicable. In the below example, “hello world” will always be logged before “happy holidays.”

    const express = require('express')
    const app = express()
    
    app.use(function(req, res, next) {
      console.log('hello world')
      next()
    })
    
    app.use(function(req, res, next) {
      console.log('happy holidays')
      next()
    })
    
    0 讨论(0)
提交回复
热议问题