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

javascript - How to handle empty route parameters in express - Stack Overflow

programmeradmin3浏览0评论

Im trying to handle an empty route parameter if a path is not specified , I would like to return a new date if the route param is empty. So far server is responding like this: Cannot GET /api/timestamp/

app.get("/api/timestamp/:date_string", function(req,res){

let dateString=req.params.date_string
 if(!req.params.date_string){
    dateString=new Date()
    res.json({"unix": dateString.getTime(), "utc" : dateString.toUTCString()})
  }  

})

Currently the server is not responding with a json new date as expected, anyone knows how to catch an empty route param?

Im trying to handle an empty route parameter if a path is not specified , I would like to return a new date if the route param is empty. So far server is responding like this: Cannot GET /api/timestamp/

app.get("/api/timestamp/:date_string", function(req,res){

let dateString=req.params.date_string
 if(!req.params.date_string){
    dateString=new Date()
    res.json({"unix": dateString.getTime(), "utc" : dateString.toUTCString()})
  }  

})

Currently the server is not responding with a json new date as expected, anyone knows how to catch an empty route param?

Share Improve this question asked May 6, 2020 at 19:02 Totony92Totony92 655 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

Express uses path-to-regexp, so you can check out that documentation here: https://www.npmjs./package/path-to-regexp#optional

You can put question mark at the end of parameters to make them optional parameters, like so .../timestamp/:date_string?

In your case you simply use:

app.get("/api/timestamp/:date_string?", function(req,res){

let dateString=req.params.date_string
 if(!req.params.date_string){
    dateString=new Date()
  }  
  res.json({"unix": dateString.getTime(), "utc" : dateString.toUTCString()})
})

You can simply check any variable or value exists or not,

if(variable){
   // this condition executed only when the variable has value.
}

if(variable) returns true when the giver variable is not

  • Undefined
  • null
  • NaN

AND

it also has some value

You do well in checking if your parameter exists. But you have your response only in that if block. I moved it out of the if block so that you will always send a response. Noy only if req.params.date_string doesn't exist.

Edit: I added furthermore the question mark to indicate that your URL parameter is optional, as pointed out in the answer from justin.

app.get("/api/timestamp/:date_string?", function(req,res){
let dateString=req.params.date_string
 if(!req.params.date_string){
    dateString=new Date()
  }  
  res.json({"unix": dateString.getTime(), "utc" : dateString.toUTCString()})
})
发布评论

评论列表(0)

  1. 暂无评论