koa的简单用法和写法。

303 阅读1分钟

koa的用法。

1、创建一个页面先用npm init -y 创建一个package.json用来安装插件。 2、安装一个koa ,还有一个koa-router 3、安装一个nodemon 然后在package.json里面写运行的代码

创建一个app.js

const Koa = require('koa');
const Router = require('koa-router');

//koa实例化
const app = new Koa();
const router = new Router();

router.get('/home',async ctx=>{
  ctx.body="hello World111";
})

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000,()=>{
  console.log('服务启动了')
})
module.exports = router

package.json页面写运行的一行代码

start这一行使用nodemon 运行app..js的代码

  "name": "jiekou",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "jsonwebtoken": "^8.5.1",
    "koa": "^2.13.4",
    "koa-body": "^4.2.0",
    "koa-router": "^10.1.1",
    "mongoose": "^6.0.13",
    "start": "^5.1.0",
    "svg-captcha": "^1.4.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}

拆分路由的模块

1、先创建一个routers文件夹 2、在文件夹里面写每一个模块 user.js模块 访问这个页面的/users可以显示数据的模块

const Koa = require('koa');
const Router = require('koa-router');

const user = require('./routes/user.js')

//koa实例化
const app = new Koa();
const router = new Router();
// 总路由添加前缀/api,总地址变为http://localhost:3000/api
router.prefix('/api')

router.get('/',async ctx=>{
  ctx.body="hello World111";
})


// 子路由添加前缀/users,最后访问地址变为http://localhost:3000/api/users/user
router.use('/users',async ctx=>{
    ctx.body='数据模块'
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000,()=>{
  console.log('服务启动了')
})