简体   繁体   English

如何处理express中的空路由参数

[英]How to handle empty route parameters in express

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/到目前为止,服务器的响应如下: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?目前服务器没有按预期响应 json 新日期,有人知道如何捕获空路由参数吗?

Express uses path-to-regexp, so you can check out that documentation here: https://www.npmjs.com/package/path-to-regexp#optional Express 使用 path-to-regexp,因此您可以在此处查看该文档: https://www.npmjs.com/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?您可以在参数末尾加上问号,使它们成为可选参数,例如.../timestamp/:date_string?

You do well in checking if your parameter exists.您在检查参数是否存在方面做得很好。 But you have your response only in that if block.但是你只有在那个 if 块中有你的回应。 I moved it out of the if block so that you will always send a response.我将它移出 if 块,以便您始终发送响应。 Noy only if req.params.date_string doesn't exist.仅当req.params.date_string不存在时才不会。

Edit: I added furthermore the question mark to indicate that your URL parameter is optional, as pointed out in the answer from justin.编辑:我还添加了问号,以表明您的 URL 参数是可选的,正如贾斯汀的回答中所指出的那样。

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()})
})

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 if(variable) 当给定变量不是时返回 true

  • Undefined不明确的
  • null null
  • NaN

AND

it also has some value它也有一些价值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM