使用titbit开发Web后端服务02:路由和参数
路由和请求类型
HTTP的起始行给出了请求类型,也被称为:请求方法。目前的请求方法:
GET POST PUT DELETE OPTIONS TRACE HEAD PATCH
最常用的是前面5个。对于每个请求类型,router中都有同名但是小写的函数进行路由挂载。为了方便调用,在初始化app后,可以使用app上同名的快捷调用。(框架层面仅支持这些。)
示例:
1 'use strict'; 2 3 const titbit = require('titibit'); 4 5 var app = new titbit({ 6 debug: true 7 }); 8 9 app.get('/', async c => { 10 c.res.body = 'success'; 11 }); 12 13 app.get('/p', async c => { 14 c.res.body = `${c.method} ${c.routepath}`; 15 }); 16 17 app.post('/', async c => { 18 //返回上传的数据 19 c.res.body = c.body; 20 }); 21 22 app.put('/p', async c => { 23 c.res.body = { 24 method : c.method, 25 body : c.body, 26 query : c.query 27 }; 28 }); 29 30 //默认监听0.0.0.0,参数和原生接口listen一致。 31 app.run(8080);
获取URL参数和表单数据
1 'use strict'; 2 3 const titbit = require('titbit'); 4 5 var app = new titbit(); 6 7 var {router} = app; 8 9 router.get('/q', async c => { 10 //URL中?后面的查询字符串解析到query中。 11 c.res.body = c.query; //返回JSON文本,主要区别在于header中content-type为text/json 12 }); 13 14 router.post('/p', async c => { 15 //POST、PUT提交的数据保存到body,如果是表单则会自动解析,否则只是保存原始文本值, 16 //可以使用中间件处理各种数据。 17 c.res.body = c.body; 18 }); 19 20 app.run(2019);
send函数
send函数就是对c.res.body的包装,其实就是设置了c.res.body的值。并且支持第二个参数,作为状态码,默认为200。
1 app.get('/', async c => { 2 c.send('success') 3 }) 4 5 app.get('/randerr', async c => { 6 let n = parseInt(Math.random() * 10) 7 if (n >= 5) { 8 c.send('success') 9 } else { 10 //返回404状态码 11 /* 12 等效于: 13 c.status(404) 14 c.res.body = 'not found' 15 */ 16 c.send('not found', 404) 17 } 18 }) 19 20 app.run(1234)
路由参数
1 app.get('/:name/:id', async c => { 2 //使用:表示路由参数,请求参数被解析到c.param 3 let username = c.param.name; 4 let uid = c.param.id; 5 c.res.body = `${username} ${id}`; 6 }); 7 app.run(8000);
任意路径参数
* 表示任意路径,但是必须出现在路由最后。
1 app.get('/static/*', async c => { 2 //*表示的任意路径解析到c.param.starPath 3 let spath = c.param.starPath 4 5 c.send(spath) 6 })
源代码地址:
安装
npm install titbit

浙公网安备 33010602011771号