1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

App.use() Method Explanation In Express Js

Discussion in 'Programming' started by Sahan Pasindu Nirmal, Jul 10, 2018 at 8:23 PM.

  1. Sahan Pasindu Nirmal

    Sahan Pasindu Nirmal Member

    Jun 29, 2018
    Likes Received:
    Trophy Points:
    I have big doubt in Express.js use() meth0d. In the most of examples i seen use() method used but i have no idea how it is works. I know express.js use so many routing methods like post(), get(), put() but i have problem in this use() method. I found on the internet this statement

    "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. Each app.use(middleware) is called every time a request is sent to the server."

    "Each app.use(middleware) is called every time a request is sent to the server." this mean if i configure request methods like post, get etc. before the all those request methods this app.use() method will call 1st?

    In the official Express.js documentation i seen this code section

    // this middleware will not allow the request to go beyond it
    app.use(function(req, res, next) {
      res.send('Hello World');
    // requests will never reach this route
    app.get('/', function (req, res) {
    Routes can handle various ways but in simple we can use get, post.. methods but what is the advantage of app.use() method? where i want use it?

    Please some one help me solve this matter. Thank you

Share This Page