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/ad/123
where id is 123. But I can't do example/ad/create
anymore, any way to check the type of the param?
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./ad/123
where id is 123. But I can't do example./ad/create
anymore, any way to check the type of the param?
- 1 Why you just don't create separate route above for /ad/create? In this case, if it will match, your route /ad/:id will not be triggered, and if you will have /ad/123 then create route will not be triggered. You have two logically different operations, so they should be in a different routes and even with a different HTTP methods. – Artsiom Miksiuk Commented Sep 9, 2017 at 8:33
-
1
Why not use a
POST
to create your ad?GET
is due to retrieve resources not create them. – CodingNagger Commented Sep 9, 2017 at 11:17
2 Answers
Reset to default 6router.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
});
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 */ })