ItsJay
ItsJay

Reputation: 198

does the order of routes matter in Express?

im trying to build this simple CMS with Restfull routes in Express.js ,

it was working just fine . then i tried to change it a lil bit so that my routes get neater(or not) .so i moved router.get('/new') route below router.post('/') route and it just stopped working as normal. when i try to get /new route the request goes to router.get('/')

this is the related part of my app.js (removed the unnessary parts)

var express=require('express'),
blogRoutes =require('./routes/blogs.js'),
app        =express();

app.use('/blogs',blogRoutes);

and this is my blogs route in blogs.js file (removed unnessary parts)

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


router.get('/',function(req,res){...});
router.get('/:id',function(req,res){...});

router.post('/',function(req,res){...});
router.get('/new',function(req,res){...});

router.get('/:id/edit',function(req,res){...});
router.put('/:id',function(req,res){...});
router.delete('/:id',function(req,res){...});

so i want to know how does this work cuz i did not find anything usefull about the order of routes other than the RESTfull routes images on net that new is before create routes.yet it does make any sense why it can't process it correctly .

Upvotes: 2

Views: 4557

Answers (2)

Ömürcan Cengiz
Ömürcan Cengiz

Reputation: 2159

From Express docs:

A route will match any path that follows its path immediately with a “/”.

For example: app.use("/apple", ...) will match “/apple”, “/apple/images”,“/apple/images/news”,

and so on.

It is a healthy approach to move router.get('/',function(req,res){...}); to the bottom.

If you move router.get('/:id',function(req,res){...}); below router.get('/new',function(req,res){...}); that should fix your problem. It is good idea to put router.get('/:id' before router.get('/:id/edit'.

Upvotes: 3

Beto
Beto

Reputation: 792

Try moving router.get('/',function(req,res){...}); to the bottom of the list, that's the root router.

Upvotes: 0

Related Questions