使用titbit开发Web后端服务01:简介和最小示例

关于titbit

titbit是Node.js的后端开发框架,因为当时教学以及开发任务的需要,最早开发了awy,恰好当时Node.js的Promise功能完善了,并且不久又支持了async/await。当时LTS的主版本是8。所以综合考虑后,使用async和await开发了最初的框架awy,当时的设计并不是很好,不过却支撑了当时的教学任务,并且还开发了一个本地Web客户端。

后来,在一个暑假,经过一番折腾,最后确定了开发titbit,设计和开发都是我一个人完成的,经过2年的更新,目前可以保证能完美的支撑大部分web后端业务,尤其在中小型服务以及微服务方面,则利用Node.js更加适合。

源代码地址:

gitee(码云)

github

安装

npm install titbit

最小示例

 1 const titbit = require('titibit')
 2 
 3 const app = new titbit()
 4 
 5 //router中的路由方法在app中都有同名的快速调用方法。
 6 var {router} = app
 7 
 8 //也可以直接使用app.get
 9 router.get('/', async c => {
10   //c是请求上下文对象,包括解析后的请求数据和处理函数
11   //返回数据只需要设计c.res.body
12   c.res.body = 'success'
13 })
14 
15 //默认监听0.0.0.0,参数和原生接口listen一致。
16 app.run(1234)

 

添加多个路由

'use strict';

const titbit = require('titibit')

var app = new titbit({
  debug: true
})

app.get('/', async c => {
  c.res.body = 'success'
})

app.get('/p', async c => {
  c.res.body = `${c.method} ${c.routepath}`
})

app.post('/', async c => {
  c.res.body = c.body
})

app.put('/p', async c => {

  c.res.body = {
    method : c.method,
    body : c.body,
    query : c.query
  }
  
})

app.run(8080)

 

获取URL参数和表单数据

'use strict';

const titbit = require('titbit')

var app = new titbit()

app.get('/q', async c => {
  //URL中?后面的查询字符串解析到query中。
  //返回JSON文本,主要区别在于header中content-type为text/json
  c.res.body = c.query
})

app.post('/p', async c => {
  //POST、PUT提交的数据保存到body,如果是表单则会自动解析,否则只是保存原始文本值.
  c.res.body = c.body
});

app.run(1234)

 

posted @ 2020-12-25 05:48  简单的机械键盘  阅读(129)  评论(0)    收藏  举报