express中req请求,取参数的三种方法 req.params req.query req.body

4,336 阅读1分钟

req.params req.query req.body
其中req.params,req.query是用在get请求当中。

用req.params 解析下面网址
http://localhost:3000/10
app.get("/:id",function (req,res) {
res.send(req.params["id"]);
});
得到/后面的内容10

用req.query 解析下面网址
http://localhost:3000/?id=10
app.get("/",function (req,res) {
res.send(req.query["id"]);
});
得到的是?后id的值 10

req.body
body不是nodejs默认提供的,你需要载入body-parser中间件才可以使用req.body;
此方法通常用来解析POST请求中的数据