Charles Rajendran Charles Rajendran - 4 months ago 10
Node.js Question

Error on separating the router file in express js 4

I am new to Node and Express, i like to separate the route function in a separate files, but i get error all the time.

my app.js file -

var express = require('express');

var index = require('./Routes/index');

var app = express();

app.use(index);

app.listen(2000);

console.log("Server working at port 2000");


My Routes/index.js

var express = require('express');
var router = express.Router();

router.use(function(req,res,next){
console.log("url "+req.url);
});

router.get('/',function(req,res){
res.send("Hi is it working?");
});

module.export = router;


When i run it, says error such as

app.use() requires middleware functions


If i put

`app.use('/',index);`


instead of
app.use(index);

then i got error like this

Router.use() requires middleware function but got a Object

Answer

So as a summary (and a correct answer) you had two issues:

Typo:

module.export = router; should be module.exports = router;.

Middleware:

Your middleware should call next() to pass the request to the next function. For more details take a look at the documentation.