Resquest
app.use(async ctx => {console.log(ctx)})
{request: {method: 'GET',url: '/api',header: {host: 'localhost:3000',connection: 'keep-alive','upgrade-insecure-requests': '1','user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9','sec-fetch-site': 'none','sec-fetch-mode': 'navigate','sec-fetch-user': '?1','sec-fetch-dest': 'document','accept-encoding': 'gzip, deflate, br','accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',cookie: 'Webstorm-334e7daa=de050401-d5fe-47cc-b339-d4a2eb60329e'}},response: {status: 404,message: 'Not Found',header: [Object: null prototype] { vary: 'Origin' }},app: { subdomainOffset: 2, proxy: false, env: 'development' },originalUrl: '/api',req: '<original node req>',res: '<original node res>',socket: '<original node socket>'}
可以拿到请求的方法请求体,响应等信息
api url
koa-router 路由
安装
$ npm install -S koa-router
尝试使用 koa-router
// index.jsconst koa = require('koa')const Router = require('koa-router')const app = new koa()const router = new Router()router.get('/', ctx=>{ctx.body = 'Hello World!'})router.get('/api', ctx=>{ctx.body = 'Hello Api!'})app.use(router.routes()).use(router.allowedMethods()) // 拦截应用里没有的请求,可以返回 404 之类错误app.listen(3000)
运行 index.js 查看是否生效
node index.js
运行成功截图


ctx,async

// middlewareconst Koa = require('koa')const app = new Koa()const middleware = function async(ctx, next) {console.log('这里是中间件0')next()// 如果没有next,则不会继续执行其他中间件console.log('中间件0-结束')}const middleware1 = function async(ctx, next) {console.log('这里是中间件1')next()console.log('中间件1-结束')}const middleware2 = function async(ctx, next) {console.log('这里是中间件2')next()console.log('中间件2-结束')}app.use(middleware)app.use(middleware1)app.use(middleware2)app.listen(3000)
node middleware.js打印结果:这里是中间件0这里是中间件1这里是中间件2中间件2-结束中间件1-结束中间件0-结束# 类似于洋葱模型
async await
//index.js//...router.get('/async', async (ctx) => {let result = await new Promise((resolve) => {setTimeout(function () {resolve('Hello 2s later')}, 2000)})ctx.body = result})//...// 用同步的写法完成异步的操作,等 await 执行完成才会继续执行
