skip to Main Content

This is the code I was working on:

import express from 'express'
import * as blogControler from '../controler/blogControler.js'
import * as authControler from '../controler/authControler.js'

const blogRouter= express.Router()

blogRouter.use(authControler.isVerified)

blogRouter.route('/allblogs').get(blogControler.showallblogs)
blogRouter.route('/:id').get(blogControler.find_blog)
blogRouter.route('/newblogs').get(blogControler.newpost)


export default blogRouter;

When I tried to hit /newblogs endpoint it was throwing error.

I tried many things and finally when I changed the position of /newblogs endpoint it worked!!
The updated code is given below –

import express from 'express'
import * as blogControler from '../controler/blogControler.js'
import * as authControler from '../controler/authControler.js'

const blogRouter= express.Router()

blogRouter.use(authControler.isVerified)

blogRouter.route('/allblogs').get(blogControler.showallblogs)
blogRouter.route('/newblogs').get(blogControler.newpost)
blogRouter.route('/:id').get(blogControler.find_blog)

export default blogRouter;

It is confusing /:id and /newblogs. I noticed that when I was calling /newblogs in the first code snipet it was calling function related to /:id. I think it is confusing the route between /:id and /newblogs.

But why is that happening?

2

Answers


  1. This is happening beacuse the router interprets a requst to /newblogs as a parameter of /:id, so basicly like someone trying to get a blog with the id of newblogs. As you showed this can be fixed simply by changing the order of the routes.

    Login or Signup to reply.
  2. This issue due to /:id overwrite /newblog URL because /:id is dynamic URl

    so if you changing the order of the routes you will still get conflict between /:id and /newblog

    so i suggest change /:id URL as below it will solve issue

        import express from 'express'
        import * as blogControler from '../controler/blogControler.js'
        import * as authControler from '../controler/authControler.js'
    
        const blogRouter= express.Router()
    
        blogRouter.use(authControler.isVerified)
    
        blogRouter.route('/allblogs').get(blogControler.showallblogs)
    
        //route changed
        blogRouter.route('/blogs/:id').get(blogControler.find_blog)
        blogRouter.route('/newblogs').get(blogControler.newpost)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search