Express router

Server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var express = require("express");
var app = express();

var api1 = require("./api1.js");
var api2 = require("./api2.js");

app.use(function(req, res, next) {
console.log("Middleware called....");
next();
});

var auth = function (req, res, next) {
console.log("Authentication process check ");
next();
};

api1.setAuth(auth);
api2.setAuth(auth);

app.use("/v1", auth, api1);
app.use("/v2", auth, api2);

app.listen(4500, function(){
console.log("App started on port 3000");
});

 

api1.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var express = require("express");

var api = express.Router();

var auth;

api.setAuth = function(auth){
this.auth = auth;
}

api.get("/timezone", function(req, res){
res.send("Time zone 1");
});

module.exports = api;

 

api2.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var express = require("express");

var api = express.Router();

var auth;

api.setAuth = function(auth){
this.auth = auth;
}

api.get("/timezone", function(req, res){
res.send("Time zone 2");
});

module.exports = api;