Reputation: 125
Does positioning your route codes matter?
The reason I ask is because when I position my res.render("new") code lower towards the page, the routing didn't work. If I put it higher on top, it routes accordingly. Example,
router.get("/tag/:id", controller.showBlog);
router.get("/:id/edit", controller.editBlog);
router.get("/new", function (req, res) {
res.render("new")});
Code above.. Fail to route to new.ejs... no error, pushes me back to index.
router.get("/new", function (req, res) {
res.render("new")});
router.get("/tag/:id", controller.showBlog);
router.get("/:id/edit", controller.editBlog);
Code above.. Able to route to new.ejs
UPDATE solved.
Although sample code shown is not exactly as above, it is indeed due to a get("/:id") route above the get("/new") that causes ("/:id") to be called before reaching ("/new"). In order words, positioning your Routes are important.
I also ran set DEBUG=express:* & node app.js
Here's the log for the working desired outcome.
Here' the log for the incorrect placement of my Routing code.
A Line item that show's something's not right.
Upvotes: 1
Views: 347
Reputation: 696
It's difficult to debug with just that code, but you may have luck using express's debug mode to see exactly why the strange behavior is occurring:
Launch the app using:
DEBUG=express:* node index.js
https://expressjs.com/en/guide/debugging.html
Upvotes: 1
Reputation: 1069
Are these the only routes in your application? For the routes you have described, it shouldn't matter. But consider the following:
app.get('/:id', function (req, res) {
// this will match all /a, /b .. including /new
res.end('done!');
});
app.get('/new', function (req, res) {
// this is never called
res.end('done!!');
});
In the above scenario, /new
handler will never be called.
Upvotes: 2
Reputation: 2373
You should wrap showBlog
and editBog
in anonymous functions. Also i'm not sure about the syntax controller.showBlog
or controller.showBlog()
With anonymous function:
router.get("/tag/:id", (req,res)=>{controller.showBlog()});
router.get("/:id/edit",(req,res)=>{controller.editBlog()});
router.get("/new", function (req, res) {
res.render("new")});
Upvotes: 0