2

I was trying to comprehend when do we need to use app.use in our node Express

While searching on web, I stumbled on this answer on reddit stating the difference between app.get and app.use

Based on which, I was able to summarise the following things.

app.use act as a super route or middleware? meaning that it gets called on every route written below/after app.use?

Also, would appreciate if someone could add more information/practise about app.use.

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210

3 Answers3

7

When using ExpressJS with NodeJS you can use app.get and app.use for several useful aspects.

After initializing your App like let app = express();, you can find below some examples:

app.use(...)

As you correctly pointed, it is useful for "middlewares", it will apply to all the GETs, POSTs, etc. you indicate afterwords. For example, you can use a Middleware only before the GETs you want to be "with user/pass authentication".

  • Indicate the folder for static contents: app.use(express.static(__dirname + "/public"));

  • Including a parser for JSON contents: app.use(bodyParser.json());

  • Define the "Cookie Parser" signing string: app.use(cookieParser("Signing text example"));

  • Separate Routers for your URLs in different files: app.use("/api", apiRouter); or app.use("/news", newsRouter); or app.use("/", siteRouter);

  • For a custom error handler: app.use(sites404handler); or app.use(globalErrorHandler);

app.get(...)

When talking about app.get(...) you are indicating which URLs will be visited via a GET method. But you can use several options here:

  • Indicate you have a home page: app.get("/", function(req, res) { res.send("Hello world!"); });

  • Accept POST requests: app.post("/", function(req, res) { res.send("Hello world! With POST call."); });

  • You can also separate it in another file as "apiRouter.js" and include there: let router = express.Router(); router.route("/books").get(function(req, res) { res.send("/api/books/ called via a Router"); });

app.set(...)

Remember that you also have the option app.set(...). This is useful for example to define View Engines like Handlebars (.hbs files).

Hope this can help!

Emi
  • 86
  • 4
2
  1. Use for static path

    //Set static path
    app.use(express.static(__dirname + '/public'));
    
  2. use as router

    //user
    app.use('/', require('./controllers/user'));
    
  3. use for handline middleware

    //Body-parser
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: true
    }));// Body parser use JSON data
    
  4. Use for custom middleware

    // force https
    app.use ( (req, res, next) =>{
        if (req.secure) {
            // request was via https, so do no special handling
            next();
        } else {
            // request was via http, so redirect to https
            res.redirect('https://' + req.headers.host + req.url);
        }
    });
    
Malay M
  • 1,659
  • 1
  • 14
  • 22
  • Malay, Just to confirm. Saying this would be correct: **app.use act as a super route or middleware? meaning that it gets called on every route written below/after app.use?** – Alwaysblue Oct 14 '18 at 12:38
  • 1
    it can be use as both, even router is also a middleware :) – Malay M Oct 14 '18 at 12:39
  • @KuchBhi to use `app.use()` as a super router the first param is `/`, that is the top route – Malay M Oct 14 '18 at 12:40
1

app.get route handler is applied to GET requests, either for specified paths or all paths:

Routes HTTP GET requests to the specified path with the specified callback functions.

app.use middleware is applied to all requests, either for specified paths or all paths:

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

use is used to apply some logic (middleware) to specific route or entire application, regardless of request method.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565