sac Dahal sac Dahal - 2 months ago 8
Node.js Question

NodeJs + ExpressJS: router level middleware not able to take the request

I am making REST calls to my server. Now when I design my codes to handle routes in application level its working without any problems. But when I handle it using router level middleware its not working,

var https = require("https");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');

var routes = require('./server'); //require server directory

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
app.listen(3000);
module.exports = app;


This is my server directory where I have a file index.js
And when I try to handle the request here using router its not taking the request. I am able to require the page to my app.js but just the router thing is not working.

var https = require("https");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var gh = require('parse-github-url'); // use to break the url user provides into various parts
var moment = require('moment'); // for Parse, validate, manipulate, and display dates in JavaScript.
var router = express.Router();
var Promise = require('bluebird');
var _ = require('underscore-node');

router.post('/click', function(req, res){
console.log("ewewew");
});


module.exports = router;


When I keep try to handle the request in my application app.js its working fine.
For Eg:

// If I keep it here it in app.js its working fine.
app.post('/click',function(){
console.log("dwfe");
})

Answer

You have to register the router with app as shown below

app.use('/',router);

Refer express documentation

express.Router() just creates another Router, a isolated middleware instance. It has to be added to app middleware stack for it to be actually invoked.