KOA基础使用
KOA简单使用
项目中npm i koa -S
还得引入npm i koa-router -S 用来配置路由
const Koa = require('koa') //引入koa
const router = require('koa-router')()//引入koa-router 并且实例化他,注意引入的方式
const app = new Koa() //将koa实例化
//配置中间件 相当于路由
router.get('/', async (ctx)=> {
ctx.body = '首页'
}).get('/index', async (ctx) => {
ctx.body='新闻'
})
app.use(router.routes()).use(router.allowedMethods())//router.routes()启动路由 router.allowedMethods()可以配置可以不配置
// 监听端口
app.listen(4100, () => {
console.log('服务器启动成功');
})
ctx.query
相当于ctx.request.query
获取get传值 下面是打印的结果ctx.querystring
相当于ctx.request.querystring
获取的get传值ctx.request
获取请求信息ctx.params
动态路由传值
总结:ctx.query打印的结果是对象形式 , 而querystring获取的是字符串形式 , ctx.request获取请求信息,并且在请求的时候可以省略request,比如
ctx.request.url
,可以写成ctx.url
ctx.params动态路由传值
KOA脚手架
1.
全局安装
npm i koa-generator -g
2.
创建项目
koa demo
3.
安装依赖
npm i 或者 yarn
4.
查看版本
koa -V
5.
启动项目
npm start
要求node.js版本在8.x以上
还没有评论,来说两句吧...