npm init -y
前端
安裝koa2node
npm install koa --save
mongodb
項目根目錄 新建 index.js數據庫
//這是最基本的服務 const Koa = require('koa'); const app = new Koa(); app.use(async(ctx)=>{ ctx.body = '<h1>hello world</h1>' }); app.listen(3000,()=>{ console.log('[server]started at port 3000....') })
本地安裝mongodb數據庫。npm
添加環境變量 ,按提示建立文件夾。 data/db/api
安裝 robo3數據庫可視化工具。跨域
安裝mongooseapp
npm install mongoose --save
cors
npm install --save bcrypt
schema 文件以下koa
const bcrypt = require('bcrypt'); const SALT_WORK_FACTOR = 10; //加鹽位數 //建立User Schema const userSchema = new Schema({ UserId: ObjectId, userName:{unique:true,type:String }, password:{type:String}, createAt:{type:Date,default:Date.now()}, lastLogin:{type:Date,default:Date.now()} },{collection:'user'}) userSchema.pre('save',function(next){ bcrypt.genSalt(SALT_WORK_FACTOR,(err,salt)=>{ if(err) return next(err); bcrypt.hash(this.password,salt,(err,hash)=>{ if(err) return next(err) this.password = hash; next(); }) }) }); //發佈模型 mongoose.model('User',userSchema);
init.js
const mongoose = require('mongoose'); const db = 'mongodb://localhost/simle-db'; const glob = require('glob'); //須要安裝 const { resolve } = require('path'); //node內置 exports.initSchemas = () => { glob.sync(resolve(__dirname,'./schema','**/*.js')).forEach(require) } exports.connect = () => { //鏈接數據庫 mongoose.connect(db); let maxConnectTimes = 0; return new Promise((resolve,reject)=>{ //增長數據庫監聽事件 斷開鏈接 mongoose.connection.on('disconnected',()=>{ console.log('*****數據庫斷開') if(maxConnectTimes < 3){ mongoose.connect(db) maxConnectTimes++; }else{ reject(); throw new Error('數據庫出現問題...') } // 錯誤 }) mongoose.connection.on('error',(err)=>{ console.log('*****數據庫錯誤') if(maxConnectTimes < 3){ mongoose.connect(db) maxConnectTimes++; }else{ reject(err); throw new Error('數據庫出現問題...') } }) //連接打開時 mongoose.connection.once('open',()=>{ console.log('mongDB connected successfully... ') resolve(); }) }) }
const { connect ,initSchemas } = require('./database/init.js'); ;(async ()=>{ await connect(); initSchemas(); })()
npm install --save koa-router
const Router = require('koa-router'); let user = require('./appApi/user.js'); let home = require('./appApi/home.js'); // 裝載全部子路由 let router = new Router(); router.use('/user',user.routes()) router.use('/home',home.routes()) // 加載路由中間件 app.use(router.routes()) app.use(router.allowedMethods())
npm install --save koa-bodyparser koa2-cors
//index.js // 接收請求的中間件 const bodyParser = require('koa-bodyparser'); // 支持跨域的中間件 const cors = require('koa2-cors'); const bodyParser = require('koa-bodyparser'); // 支持跨域的中間件 const cors = require('koa2-cors'); //這兩個是須要放到其餘app.use操做以前才生效 app.use(bodyParser()) app.use(cors())
const Router = require('koa-router'); let router = new Router(); const mongoose = require('mongoose'); router.get('/',async(ctx)=>{ ctx.body= "這是用戶操做首頁" }) router.post('/register',async(ctx)=>{ // console.log('------11') // console.log(ctx.request.body); // console.log('------11') // ctx.body = ctx.request.body; //取得model const User = mongoose.model('User'); //把從前端接收的POST數據封裝成一個新的user對象 let newUser = new User(ctx.request.body); //使用mongoose的save方法直接存儲,而後判斷是否成功 await newUser.save().then(()=>{ //保存成功 返回code == 200,並返回成功信息 ctx.body = { code : 200, msg:"註冊成功" } }).catch(error =>{ //失敗返回 code = 500,返回錯誤信息 ctx.body = { code: 500, message:error } }) }) module.exports = router;