Reputation: 2804
In express.js, if I have this route in my server side
router.get('/ad/:id', (req, res) => {
const { id } = req.params
Ad.getAd(id, (err, resp) => {
if(err){
return handleError('Failed to load an ad', res)
}
res.json({
success: true,
result: resp
})
})
})
and it worked fine I want to load a detail ad like example.com/ad/123
where id is 123. But I can't do example.com/ad/create
anymore, any way to check the type of the param?
Upvotes: 3
Views: 3997
Reputation: 3766
You can create separate route for it. Place before /ad/:id
route, because it's catching all requests like /ad/*
.
router.get('/ad/create', (req, res) => { /* some work */ })
router.get('/ad/:id', (req, res) => { /* some work */ })
Since you mentioned you are building a SPA, you must redirect all GET requests to react-router:
app.get("*", function (req, res) {
res.sendFile(__dirname + "/path/to/index.html")
})
Also you can prepend api
to all back-end endpoints to prevent ambiguity.
router.get('/api/ad/create', (req, res) => { /* some work */ })
router.get('/api/ad/:id', (req, res) => { /* some work */ })
Upvotes: 4
Reputation: 138267
router.get('/ad/:id', (req, res,next) => {
const { id } = req.params
if(! parseInt(id,10)){
return next();//skip this route if not a number
}
//its a number
});
Upvotes: 6