Search code examples
node.jsexpressmiddleware

Why is Middleware not working in express js


I am trying to learn middleware in express js. Could anyone help where I am missing? Here is my code

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');

var app = express();

app.use("/", function(req, res, next){
  console.log("this is my second output");
  next();
});

app.get('/', function(req,res){
  console.log("this is my first output");
//res.send('Hello World');
});

app.listen(3000, function(){
  console.log('Server started on port 3000...');
})

I am getting Server started on port 3000.. when I run on cmd and getting "page is not working" on localhost:3000

Edited

I got

Server started on port 3000...
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output
this is my second output
this is my first output

after some time. But localhost:3000 is still not working


Solution

  • enter image description here

       var express = require('express');
        var bodyParser = require('body-parser');
        var path = require('path');
    
        var app = express();
        // use this middleware to pass all the requests
        app.use("/", function(req, res, next){
          console.log("this is my second output");
        // move to next middleware
          next();
        });
        //handle all the get requests to localhost:3000 url
        app.get('/', function(req,res){
          console.log("this is my first output");
        // send the response
        res.send('Hello World');
        // or you can send the response like this 
        // res.json(JSON.stringify({"success":"true"}));
        });
    
        app.listen(3000, function(){
          console.log('Server started on port 3000...');
        })
    

    send a get request to http://localhost:3000