Reputation: 3153
I am getting paramter from default route like this
conf.js: router.use('/' ,require('./hello'));
hello.js:
router.get('/:param', async (req,res)=>{
try{
let { param }= req.params;
console.log(param)
let param = await Params.findOne({param});
if(!param){
return res.redirect('/not-found')
}
})
and when i visit to any url that i am handling or not handling (like this: router.use('/blah',require('./blah'));
)
the code above handles it, so how can i prevent that and let the actual handler handle it? for example when i am redirected to /not-found this is actual /not-found handler
router.get('/', async (req,res)=>{
try{
res.render('notfound')
}catch(err){
return res.redirect(url.format({
pathname: '/error',
query: {
message: err.message
}
}))
}
})
but it is handled as /:param
Upvotes: 1
Views: 36
Reputation: 1102
if I understand you , you need to set this route /:param
at the end of your routers chain
router.use('/blah',require('./blah'))
//then
router.get('/:param', async (req,res)=>{
try{
let { param }= req.params;
console.log(param)
let param = await Params.findOne({param});
if(!param){
return res.redirect('/not-found')
}
})
so your request will arrive on the first route if it doesn't match it will go to the second one
Upvotes: 1
Reputation: 7572
Express routes and middleware are order-dependent. Everying you add to app
via use
, get
, post
, etc. is actually one long chain of possible matches for the URL.
If the first route you add matches everything (at least, everything with only one path component) then sure enough, that route is going to match everything.
The solution is to add more specific routes like app.get('/people')
first, and catch-alls like app.get('/:param')
last.
As for the "not found" case however, I do not understand why you would expect this to fire at all. Of course any one-path-component path will match the /:param
route. So perhaps what you really want is to match only certain values of param. For that, Express supports regex rules. There is a good explanation here.
Upvotes: 2