基本功能
实现一个get请求定义
app.use(async(ctx,next)=>{const { path, method } = ctxif (path === '/classic' && method === 'GET') {// ctx.body = 'classic'// return jsonctx.body = {key:'classic'}}})
定义路由,并执行函数,定义返回体,写到返回的内容中。
使用第三方路由中间件
- koa-router
```javascript
const koaRouter = require(‘koa-router’)
const app = new Koa()
const Router = new koaRouter()
app.use(async(ctx,next)=>{
const { path, method } = ctx
if (path === ‘/classic’ && method === ‘GET’) {
// ctx.body = ‘classic’
// return json
ctx.body = {
} } })key:'classic'
Router.get(‘/classic’, (ctx, next) => { ctx.body = { key:’classic’ } }) app.use(Router.routes()) ``` 基本步骤:1 安装模块并实例化 2 配置路由 3 koa配置实例
小常识
REST风格对几种方法的约定
1 get查询
2 post新增
3 put 更新
4 delete 删除
