一鍵生成koa2項目:
一、 npm install -g koa-generator
二、新建項目目錄 koa mytest (koa1項目) koa2 koa2test (koa2項目)
三、進入目錄 cd koa2test
四、安裝依賴 npm install
五、運行 npm startjavascript
mongoose鏈接:前端
var mongoose = require('mongoose'); var Goods = require('../models/goods'); //鏈接MongoDB數據庫 mongoose.connect('mongodb://quan:123456@127.0.0.1:27017/material',{useMongoClient:true}); //quan ->用戶名; 123456 ->密碼 ;127.0.0.1:27017/material mongod數據庫/表 mongoose.connection.on("connected", function () { //監聽鏈接成功 console.log("MongoDB connected success.") }); mongoose.connection.on("error", function () { //監聽鏈接失敗 console.log("MongoDB connected fail.") }); mongoose.connection.on("disconnected", function () { //監聽掉線 console.log("MongoDB connected disconnected.") });
model模態java
var mongoose = require('mongoose') var Schema = mongoose.Schema; var produtSchema = new Schema({ "id":String, "url":String, "click":Number, "pv":Number, "ctr":Number, "dtus":String }); module.exports = mongoose.model('landpage',produtSchema); //material下的表,對應landpages 以下圖
koa-router:mongodb
個人項目結構,app.js 項目入口,models 模態 routes 路由數據庫
app.jsexpress
const Koa = require('koa') const app = new Koa() const router = require('koa-router')() const api = require('./routes/goods') // routes router.use('/api', api.routes(), api.allowedMethods()) app.use(api.routes())
goods.js 路由,接口邏輯npm
var router = require('koa-router')() var mongoose = require('mongoose'); var Goods = require('../models/goods'); //鏈接MongoDB數據庫 mongoose.connect('mongodb://quan:123456@127.0.0.1:27017/material',{useMongoClient:true}); mongoose.connection.on("connected", function () { console.log("MongoDB connected success.") }); mongoose.connection.on("error", function () { console.log("MongoDB connected fail.") }); mongoose.connection.on("disconnected", function () { console.log("MongoDB connected disconnected.") }); router.post("/addPv", async (ctx, next) => { //post請求 // console.log(ctx.request.body) // console.log(ctx.request.body.id) let id = ctx.request.body.id //獲取前端接口傳參 var conditions = {id: id}; var updates = {}; const res = await Goods.find(conditions).catch(err => ctx.throw(500, '服務器內部錯誤')) //數據庫查找 console.log(res) if (res) { // console.log(res[0].pv+1); if(ctx.request.body.cmd == 1001) { //1001 pv; 1002 click updates = {$set: {pv: res[0].pv+1, ctr:res[0].click/(res[0].pv+1)}}; } else if(ctx.request.body.cmd == 1002) { updates = {$set: {click: res[0].click+1, ctr:(res[0].click+1)/(res[0].pv)}}; } const up = await Goods.update(conditions, updates).catch(err => ctx.throw(500, '服務器內部錯誤')) //數據庫更新數據 console.log(up) if (up) { ctx.response.body = "更新成功" //傳給前端接口返回的值 } else { ctx.response.body = "更新失敗" } } }); module.exports = router;
中間件json
統一編寫接口返回值:api
在middlewares文件夾增長 response_formatter.jsruby
/** * 在app.use(router)以前調用 */ var response_formatter = async (ctx, next) => { //先去執行路由 await next(); //若是有返回數據,將返回數據添加到data中 if (ctx.body) { ctx.body = { code: 0, message: 'success', data: ctx.body } } else { ctx.body = { code: 0, message: 'success' } } } module.exports = response_formatter;
在app.js引用
const response_formatter = require('./middlewares/response_formatter'); //添加格式化處理響應結果的中間件,在添加路由以前調用 app.use(response_formatter);
koa2與 express區別:
一、express用 express-generator生成應用
npm install express-generator -g
在當前工做目錄下建立一個命名爲 myapp 的應用。
express myapp
cd myapp npm install
二、查詢數據庫的區別
router.post("/addPv", function (req,res,next) { console.log(req.body.id) let id = req.body.id //獲取前端傳參 var conditions = {id: id}; var updates = {}; // let obj = new Goods({url:"http://test-static.qukan.aimodou.net/wlx/image/2018/09/21/5ba4e9518093d.png",click:20,pv:1000,ctr:"2%",dtus:"2282",id:"7"}) // obj.save((err,res) => { }) Goods.find(conditions, (err,doc1) => { // 在查詢回調裏處理更新數據庫 if (err) { console.log(err); } else { // console.log(doc1[0].pv+1); if(req.body.cmd == 1001) { //1001 pv; 1002 click updates = {$set: {pv: doc1[0].pv+1, ctr:doc1[0].click/(doc1[0].pv+1)}}; } else if(req.body.cmd == 1002) { updates = {$set: {click: doc1[0].click+1, ctr:(doc1[0].click+1)/(doc1[0].pv)}}; } Goods.update(conditions, updates, function (err,doc) { // 在更新回調裏處理接口返回 console.log(err,doc) if (err) { console.error(err); res.json({ //接口返回處理跟koa2不一樣,koa2是 ctx.response.body = '' status:'-1', msg:err.message }); } else { console.error("更新成功") res.json({ status:'0', msg:'ok', }); } }); } }) });
三、路由router的區別
express在app.js
var express = require('express'); var goods = require('./routes/goods') var app = express(); app.use('/goods', goods);