koa常用模塊使用

mongoose操作數(shù)據(jù)庫

const Koa = require('koa');
const app = new Koa();
const mongoose = require('mongoose');
mongoose.connect("mongodb://118.187.4.253/vuekoamongo", (err) => {
    if (!err) {
        let testSchema = new mongoose.Schema({
            name: String,
            age: Number,
            sex: String
        });
        let myModel = mongoose.model('myModel ', testSchema, "test");
        let doc1 = new myModel({
            name: "zyw",
            age: 23,
            sex: "男"
        });
        doc1.save().then(() => {
            console.log("插入成功")
        })
    }
});

app.listen(3008)

router模塊化

當(dāng)有很多的路由的時候,就需要把路由分開,不能全部寫到app.js里面去,下面就是具體方法。
后端項目里新建一個routers文件夾,用來存放所有的路由模塊文件
routers目錄下新建各個頁面的路由文件,比如index.js(首頁路由),shop.js(購物車路由)等。
1.編輯index.js,特別注意,根目錄需要帶/,其他根下面的不需要帶/。

const Router = require('koa-router');
const router = new Router();
router.get('/', async (ctx, next) => {
    ctx.body="這是首頁"
    await next()
  });
  router.get('user', async (ctx, next) => {
    ctx.body="這是用戶中心"
    await next()
  });
  router.get('about', async (ctx, next) => {
    ctx.body="這是關(guān)于我們"
    await next()
  });

  module.exports=router;

2.app.js里面引入以上模塊

const Router=require("koa-router");//引入路由模塊
const router=new Router;
const index=require("./models/routers/index.js");//引入index文件
router.use("/",index.routes());//當(dāng)訪問根時,使用index的路由規(guī)則

app.use(router.routes());//特定寫法
app.use(router.allowedMethods());

3.制作二級目錄的路由,特別注意
二級目錄的根,放到二級目錄里來體現(xiàn)。/shop訪問時直接使用shop規(guī)則里的/規(guī)則
二級目錄的子頁面,需要加/

const Router=require("koa-router")
const router=new Router;
router.get("/",async (ctx,next)=>{
    ctx.body="這是商城首頁"
    await next()
});
router.get("/goods",async (ctx,next)=>{
    ctx.body="這是商城商品頁"
    await next()
});
router.get("/cart",async (ctx,next)=>{
    ctx.body="這是購物車頁面"
    await next()
});

module.exports=router;

然后在app.js里面加上下面兩行即可訪問
const shop=require("./models/routers/shop.js");
router.use("/shop",shop.routes());

處理密碼,把加密成密文的工具bcrypt
處理用于認(rèn)證的token的工具,Json web token (JWT)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容