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 03 Answers
Reset to default 6Express 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()})
})