Why is Middleware not working in express js

Viewed 2378

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

2 Answers

The reason you get the "page is not working" message is because your application does not respond to any request it receives.

You'll need to uncomment that res.send('Hello World'); in app.get('/', ...). After that your code works perfectly fine.

Note, however, that in the structure of your code, your middleware app.use(...) is called before you get to the main logic for the route (app.get(...)), contrary to what's indicated by your console.log calls.

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

Related