Express 应用级中间件 获取请求参数
应用程序中间件
- '/路径名/:参数名'
- 访问 localhost:port/路径名/参数值
- 提取参数:req.params {参数名:参数值}
const express = require('express');
const app = express();
//获取单个get请求参数
//http://localhost:3000/1
app.get('/:bookid',(req,res)=>{
console.log(req.params);//{ bookid: ':1' }
res.send(req.params);
});
// http://localhost:3000/id1
app.get('/id:bookid',(req,res)=>{
console.log(req.params);//{ bookid: '1' }
res.send(req.params);
});
// http://localhost:3000/id/1
app.get('/id/:bookid',(req,res)=>{
console.log(req.params);//{ bookid: '1' }
res.send(req.params);
next();
});
//提取单个参数
app.use('/user/:id',(req,res)=>{
console.log('method:',req.method);
res.send(req.params);
});
//提取多个参数
// http://localhost:3000/user/1/books/2
app.use('/user/:id/books/:booksid', (req, res) => {
console.log(req.params);
res.send(req.params);
// {
// "id": "1",
// "booksid": "2"
// }
});
//http://localhost:3000/user/1/books/10/three/3
app.use("*",(req,res)=>{
res.send(req.params);//{"0": "/user/1/books/10/three/3"}
})
app.listen(3000, () => console.log("server run at 3000..."));