最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - param type in route of express.js - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Sep 9, 2017 at 8:20 Jenny MokJenny Mok 2,8049 gold badges33 silver badges62 bronze badges 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6
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
});

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 */ })
发布评论

评论列表(0)

  1. 暂无评论