搭建koa脚手架 (koa2 my-project 一键生成)

  1. onst koa=require("koa")
  2. const app=new koa()
  3. const path=require("path")
  4. const router=require("./router/index")
  5. const bodyParser=require("koa-bodyparser") //解析请求参数
  6. const koaViews=require("koa-views")
  7. const views=path.join(__dirname,"./views")
  8. app.use(bodyParser())
  9. app.use(require("koa-static")(__dirname+"./public")) //解析静态资源
  10. app.use(koaViews(views,{
  11. extension:'html'
  12. }))
  13. app.use(router.routes(),router.allowedMethods()) //开启路由
  14. const PORT=process.env.PORT||8080 //端口号
  15. app.listen(PORT)
  16. module.exports=app

路由

  1. 一级路由
  2. const router=require("koa-router")();
  3. const userRouter=require("./user")
  4. const classRouter=require("./class")
  5. router.use("/user",userRouter.routes(),userRouter.allowedMethods()) //开启子路由
  6. router.use("/class",classRouter.routes(),classRouter.allowedMethods())
  7. module.exports=router
  1. 二级路由 user
  2. const router=require("koa-router")();
  3. const {query}=require("../mysql/index")
  4. router.post("/addUser",async ctx=>{ //向数据库中添加数据
  5. let {username,department,position,date,classname,school}=ctx.request.body;
  6. let res=await query(`insert into user(username,department,position,date,classname,school) values(?,?,?,?,?,?)`,[
  7. username,department,position,date,classname,school
  8. ])
  9. ctx.body=res
  10. })
  11. router.post("/removeUser",async ctx=>{ //从数据库中删除数据
  12. let{id}=ctx.request.body;
  13. let res=await query(`delete from user where id=${id}`)
  14. ctx.body=res
  15. })
  16. module.exports=router
  1. 二级路由 class
  2. const router=require("koa-router")();
  3. const {query}=require("../mysql/index")
  4. router.post("/search",async ctx=>{ //查询数据 多表连查
  5. let {username}=ctx.request.body;
  6. let res=await query(`select * from user where username='${username}'`)
  7. let userInfo=res[0]
  8. let result=await query(`select * from class where userid=${userInfo.id}`)
  9. ctx.body={
  10. userInfo,
  11. result:result[0]
  12. }
  13. })
  14. module.exports=router

数据库配置

  1. config
  2. module.exports={
  3. host : 'localhost',
  4. user : 'root',
  5. password : '123321',
  6. database : 'mynode'
  7. }
  1. mysql
  2. const mysql = require('mysql');
  3. const mysqlConfig=require("../config/index")
  4. const connection = mysql.createConnection({
  5. ...mysqlConfig
  6. });
  7. connection.connect();
  8. const query=($sql,options)=>{
  9. return new Promise((resolve,reject)=>{
  10. let callback=(error,result)=>{
  11. if(error){
  12. reject(error)
  13. }else{
  14. resolve(result)
  15. }
  16. }
  17. options=options?options:callback;
  18. callback=options?callback:null;
  19. connection.query($sql,options,callback);
  20. })
  21. }
  22. module.exports={query}