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

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

    Middleware is a general term for software that serves to "glue together" so app.use is a method to configure the middleware, for example: to parse and handle the body of request: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); there are many middlewares you can use in your express application just read the doc : http://expressjs.com/en/guide/using-middleware.html

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

    You can use app.use('/apis/test', () => {...}) for writing middleware for your api, to handle one or some action (authentication, validation data, validation tokens, etc) before it can go any further or response with specific status code when the condition that you gave was not qualified.

    Example:

    var express = require('express')
    var app = express()
    
    app.use(function (req, res, next) {
      // Your code to handle data here
      next()
    })
    

    More detail is, this part actually an anonymous function for you to write the logic on runtime

    function (req, res, next) {
       // Your code to handle data here
       next()
    }
    

    You can split it into another function from another file and using module.export to use

    next() here for the logic that if you handle everything is fine then you can use then for the program to continue the logic that its used to.

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

    use is a method to configure the middleware used by the routes of the Express HTTP server object. The method is defined as part of Connect that Express is based upon.

    Update Starting with version 4.x, Express no longer depends on Connect.

    The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions.

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

    app.use is Application level middleware

    Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

    you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.

    This example shows a middleware function with no mount path. The function is executed every time the app receives a request.

    var app = express()
    
    app.use(function (req, res, next) {
      console.log('Time:', Date.now())
      next()
    })
    

    reference from https://expressjs.com/en/guide/using-middleware.html

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

    The app object is instantiated on creation of the Express server. It has a middleware stack that can be customized in app.configure()(this is now deprecated in version 4.x).

    To setup your middleware, you can invoke app.use(<specific_middleware_layer_here>) for every middleware layer that you want to add (it can be generic to all paths, or triggered only on specific path(s) your server handles), and it will add onto your Express middleware stack. Middleware layers can be added one by one in multiple invocations of use, or even all at once in series with one invocation. See use documentation for more details.

    To give an example for conceptual understanding of Express Middleware, here is what my app middleware stack (app.stack) looks like when logging my app object to the console as JSON:

    stack: 
       [ { route: '', handle: [Function] },
         { route: '', handle: [Function: static] },
         { route: '', handle: [Function: bodyParser] },
         { route: '', handle: [Function: cookieParser] },
         { route: '', handle: [Function: session] },
         { route: '', handle: [Function: methodOverride] },
         { route: '', handle: [Function] },
         { route: '', handle: [Function] } ]
    

    As you might be able to deduce, I called app.use(express.bodyParser()), app.use(express.cookieParser()), etc, which added these express middleware 'layers' to the middleware stack. Notice that the routes are blank, meaning that when I added those middleware layers I specified that they be triggered on any route. If I added a custom middleware layer that only triggered on the path /user/:id that would be reflected as a string in the route field of that middleware layer object in the stack printout above.

    Each layer is essentially adding a function that specifically handles something to your flow through the middleware.

    E.g. by adding bodyParser, you're ensuring your server handles incoming requests through the express middleware. So, now parsing the body of incoming requests is part of the procedure that your middleware takes when handling incoming requests -- all because you called app.use(bodyParser).

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

    In short app.use() supports all type of requests [eg:get,post,...] so its mostly used to setup middelware. or can be used for when the routes and functions seperated

    example:

    app.use("/test",functionName)
    

    and functionName is located in different file

    0 讨论(0)
提交回复
热议问题