###mongoose操作数据库
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模块化 当有很多的路由的时候,就需要把路由分开,不能全部写到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="这是关于我们"
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());//当访问根时,使用index的路由规则
app.use(router.routes());//特定写法
app.use(router.allowedMethods());
3.制作二级目录的路由,特别注意 二级目录的根,放到二级目录里来体现。/shop访问时直接使用shop规则里的/规则 二级目录的子页面,需要加/
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 处理用于认证的token的工具,Json web token (JWT)