cod*_*bot 0 routes node.js express
我使用node.js v8.11.1并表达4.16.3。
说我有以下路线
app.get('/:id', function(req, res){
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情
if(req.params.id) then query1
else //no id param in the url
query2
Run Code Online (Sandbox Code Playgroud)
因此,我可以前往http://localhost:3000/或到达http://localhost:3000/504,路线将做出相应的响应。
但是当我去http://localhost:3000/我只是得到Cannot GET /
如何修复路线?
谢谢
使用?operator 将您的route参数设为可选。
通过以下更改路线:
app.get('/:id?', function(req, res){
现在,这两种方法都适用:http:// localhost:3000 /或http:// localhost:3000/504
我同意@n32303,你可以这样做:
app.get('/', function(req, res){
//Called when there is no id specified
}
app.get('/:id', function(req, res){
// Called when an Id is specified (req.params.id will be set )
}
Run Code Online (Sandbox Code Playgroud)
消除对 if 语句的需要
| 归档时间: |
|
| 查看次数: |
721 次 |
| 最近记录: |