Search code examples
node.jsexpressmiddleware

Difference between app.use() and app.get()


var express = require('express'); 
var app = express(); 
var PORT = 3000; 
  
// This middleware will not allow the 
// request to go beyond it 
app.use(function (req, res, next) { 
    console.log("Middleware called") 
    next(); 
}); 
    
// Requests will never reach this route 
app.get('/user', function (req, res) { 
    console.log("/user request called"); 
    res.send('Welcome to GeeksforGeeks'); 
}); 
  
app.listen(PORT, function(err){ 
    if (err) console.log(err); 
    console.log("Server listening on PORT", PORT); 
}); 

Can you explain "This middleware will not allow the request to go beyond it". infact, the output is correct but why is it written so? The code is taken from geeksforgeeks


Solution

  • What is the difference between app.use() and app.get() ? Well, GET is a HTTP method for receiving data from server. for example a HTML page. But a Middleware is an application invoked before actual server methods and you have an access to something called next() to pass request to the next route. for example you can define a middleware to check user login , if it's logged in you can pass it to the next routes.

    About that code: The comments are not correct! the middleware will allow the request to go beyond because of the next() used in middleware.