标签:att cat ring line 监听 cli class request 项目结构
一键生成koa2项目:
1、 npm install -g koa-generator
2、新建项目目录 koa mytest (koa1项目) koa2 koa2test (koa2项目)
3、进入目录 cd koa2test
4、安装依赖 npm install
5、运行 npm start
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模态
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:
我的项目结构,app.js 项目入口,models 模态 routes 路由
app.js
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 路由,接口逻辑
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;
中间件
统一编写接口返回值:
在middlewares文件夹增加 response_formatter.js
/** * 在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区别:
1、express用 express-generator生成应用
npm install express-generator -g
在当前工作目录下创建一个命名为 myapp 的应用。
express myapp
cd myapp
npm install
2、查询数据库的区别
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‘, }); } }); } }) });
3、路由router的区别
express在app.js
var express = require(‘express‘); var goods = require(‘./routes/goods‘) var app = express(); app.use(‘/goods‘, goods);
node+koa2+mongod构建项目及与express对比
标签:att cat ring line 监听 cli class request 项目结构
原文地址:https://www.cnblogs.com/s-quan/p/10096922.html