jstutorial icon indicating copy to clipboard operation
jstutorial copied to clipboard

是 req.params.id 还是 req.params.who

Open xuoutput opened this issue 2 years ago • 1 comments

这些方法的第一个参数,都是请求的路径。除了绝对匹配以外,Express允许模式匹配。

app.get("/hello/:who", function(req, res) {
  res.end("Hello, " + req.params.who + ".");
});

上面代码将匹配“/hello/alice”网址,网址中的alice将被捕获,作为req.params.who属性的值。需要注意的是,捕获后需要对网址进行检查,过滤不安全字符,上面的写法只是为了演示,生产中不应这样直接使用用户提供的值。

如果在模式参数后面加上问号,表示该参数可选。

app.get('/hello/:who?',function(req,res) {
	if(req.params.id) {   // 这里是 who 参数吧
    	res.end("Hello, " + req.params.who + ".");
	}
    else {
    	res.send("Hello, Guest.");
	}
});

xuoutput avatar Apr 01 '23 08:04 xuoutput

https://github.com/ruanyf/jstutorial/pull/339

xuoutput avatar Apr 01 '23 08:04 xuoutput