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

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

    app.use is woks as middleware for app request. syntax

    app.use('pass request format',function which contain request response onject)
    

    example

    app.use('/',funtion(req,res){
     console.log(all request pass through it);
    // here u can check your authentication and other activities.
    })
    

    also you can use it in case of routing your request.

    app.use('/', roting_object);
    
    0 讨论(0)
  • 2020-11-29 15:17

    In express if we import express from "express" and use app = express(); then app having all functionality of express

    if we use app.use()

    with any module/middleware function to use in whole express project

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

    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.

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

    app.use() acts as a middleware in express apps. Unlike app.get() and app.post() or so, you actually can use app.use() without specifying the request URL. In such a case what it does is, it gets executed every time no matter what URL's been hit.

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

    Each app.use(middleware) is called every time a request is sent to the server.

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

    app.use is a function requires middleware. For example:

     app.use('/user/:id', function (req, res, next) {
           console.log('Request Type:', req.method);
            next();
         });
    

    This example shows the middleware function installed in the /user/:id path. This function is executed for any type of HTTP request in the /user/:id path.

    It is similar to the REST Web Server, just use different /xx to represent different actions.

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