安装koa-generator脚手架,并创建一个项目
全局安装:cnpm install -g koa-generator 查看版本:koa2 --version 创建项目:koa2 project 默认的是用jade模板引擎的 koa2 -e koa2-learn 使用的是ejs模板引擎,项目名称koa2-learn 初始化:cnpm install 运行:SET DEBUG=koa* npm start localhost:3000 运行:方式二:开发模式/修改后自启动 npm run dev
安装mongoDB数据库,并安装mongoose
mongodb的概念及安装 非关系型数据库, mongoose为模型提供了一种直接的,基于scheme结构去定义你的数据模型。它内置数据验证, 查询构建,业务逻辑钩子等,开箱即用。 mongodb可视化工具RoBo 3T 安装及应用 下载地址:https://robomongo.org/download mongoose的作用 文档地址:http://www.mongoosejs.net/docs/schematypes.html 操作mongoDB数据库, mongoose的应用 安装mongoose: cnpm install mongoose
使用es6,配置babel.文件
修改package.json文件 "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server --exec babel-node", "start": "cross-env NODE_ENV=production node server/index.js --exec babel-node", 新增babel配置文件 .babelrc { "presets":["es2015"] } 下载babel-preset-es2015文件 cnpm install babel-preset-es2015 报错:'babel-node' 不是内部或外部命令,也不是可运行的程序 解决办法:执行cnpm i babel-core babel-preset-es2015 babel-cli
const session = require('koa-session'); const Koa = require('koa'); const app = new Koa(); app.keys = ['some secret hurr']; const CONFIG = { key: 'koa:sess', /** (string) cookie key (default is koa:sess) */ /** (number || 'session') maxAge in ms (default is 1 days) */ /** 'session' will result in a cookie that expires when session/browser is closed */ /** Warning: If a session cookie is stolen, this cookie will never expire */ maxAge: 86400000, autoCommit: true, /** (boolean) automatically commit headers (default true) */ overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */ renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ }; app.use(session(CONFIG, app)); // or if you prefer all default config, just use => app.use(session(app)); app.use(ctx => { // ignore favicon if (ctx.path === '/favicon.ico') return; let n = ctx.session.views || 0; ctx.session.views = ++n; ctx.body = n + ' views'; }); app.listen(3000); console.log('listening on port 3000');
使用request模块
request是服务端发起请求的工具包
// 默认是GET请求 var request = require('request'); request('您的请求url', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // 请求成功的处理逻辑 } }); // POST请求 var request = require('request'); var url="请求url"; var requestData="需要传输的数据"; request({ url: url, method: "POST", json: true, headers: { "content-type": "application/json", }, body: JSON.stringify(requestData) }, function(error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // 请求成功的处理逻辑 } }); // POST form格式上传数据 request.post({url:'', form:{key:'value'}}, function(error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // 请求成功的处理逻辑 } })
创建connectDB.js,利用mongoose连接数据库
import mongoose from 'mongoose'; const db = 'mongodb://127.0.0.1/my_test'; // 导出一个方法 exports.connect = () => { // 连接数据库 mongoose.connect(db); // 记录数据库连接的次数 let maxConnectTimes = 0; return new Promise((resolve, reject) => { // 连接成功操作 mongoose.connection.once('open', () => { console.log('Mongodb 数据库连接成功.'); resolve(); }); // 连接断开操作 mongoose.connection.on('disconnected', () => { console.log('*********** 数据库断开 ***********'); if (maxConnectTimes < 3) { maxConnectTimes++; mongoose.connect(db); } else { reject(new Error('数据库连接失败')); throw new Error('数据库连接失败'); } }); // 连接失败操作 mongoose.connection.on('error', error => { console.log('*********** 数据库错误 ***********'); if (maxConnectTimes < 3) { maxConnectTimes++; mongoose.connect(db); } else { reject(error); throw new Error('数据库连接失败'); } }); }); }
app.js代码
import Koa from 'koa' //必须使用babel import views from 'koa-views' import json from 'koa-json' import onerror from 'koa-onerror' import bodyparser from 'koa-bodyparser' import logger from 'koa-logger' const app = new Koa() // 导入数据库连接文件 import { connect } from'./utils/connectDB'; const index = require('./routes/index') const users = require('./routes/users') // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(json()) app.use(logger()) app.use(require('koa-static')(__dirname + '/public')) app.use(views(__dirname + '/views', { extension: 'ejs' })) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start // console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) // routes app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) // error-handling app.on('error', (err, ctx) => { console.error('server error', err, ctx) }); // 立即执行函数 (async () => { await connect(); // 执行连接数据库任务 })(); module.exports = app