Mir
Mir

Reputation: 75

Confusion with app.use with Router() in express

I was learning Express in Node.js and came across Router() allowing us to modularize our routes. But than I found this code:

// we'll create our routes here

// get an instance of router
var router = express.Router();

...

// route with parameters (http://localhost:8080/hello/:name)
router.get('/hello/:name', function(req, res) {
    res.send('hello ' + req.params.name + '!');
});

// apply the routes to our application
app.use('/', router);

What confused me is that why we need to use app.use('/', router); to apply the routes. That is, what if we use app.get('/', router);

Upvotes: 0

Views: 1759

Answers (3)

chayan segupta
chayan segupta

Reputation: 36

I am giving you a simple code example to make you understand the use of express.Router(). Yes you are right that it helps in modularization. Actually it makes our main app.js file clean from all the routes. We just put all those routes based on their purposes in different files and require them when needed. so suppose I have two files app.js and register.js

// app.js file's code goes here
let express = require("express")
let app = express()
let register = require("./routes/register")

app.use(register) // This will tell your app to import all those routes which are in register 
// register.js file's code goes here
let express = require("express")
let router = express.Router()

router.get("/register", callback_function);
router.post("/register", callback_function);

module.exports = router;

So basically what I am trying to show is your register.js can contain all types of HTTP requests(GET, POST, PUT,...) and when we use app.use(register) this will handle all those routes. app.get("route_path", callback_function) is only for handling get requests to that path.

Upvotes: 2

Sanket Phansekar
Sanket Phansekar

Reputation: 741

When app.use is used then it handled all the HTTP methods, but when app.get is used it takes just GET method.

Added advantage to app.use is that route will match any path that follows its path immediately with a /. For example:

app.use('/v1', ...)

will match /users, /users/accounts, /users/accounts/account-id, and so on.

Upvotes: 0

Eggon
Eggon

Reputation: 2366

Router is just a middleware of it's own. If you use app.get('/', router) you will use the router just for GET requests. Using use channels all requests there.

Upvotes: 0

Related Questions