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)