1-使用 koa 搭建服务器
1.新建site文件夹,cmd进入命令行
npm init //初始化一份package.json
2.下载koa
npm install koa --save-dev
3.创建一个应用程序 新建app.js
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
// ctx.body 即服务端响应的数据
ctx.body = 'Hello Koa';
})
// 监听端口、启动程序
app.listen(3000, err => {
if (err) throw err;
console.log('runing...');
})
4.启动
node app.js
2-如何配置 koa 路由
var koa=require('koa') var app=new koa() var Router=require('koa-router') var router=Router() router.use('/',(ctx)=>{ ctx.body='koa' }) app.use(router.routes()) .use(router.allowedMethods()) app.listen(3000,()=>{ console.log('服务器已启动,端口正在监听...') })3-静态资源如何获取
var koa=require('koa')
var app=new koa() var Router=require('koa-router') var router=Router() var path=require('path') var static=require('koa-static') app.use(static(path.join(__dirname,'public'))) router.use('/',(ctx)=>{ ctx.body='koa' }) app.use(router.routes()) .use(router.allowedMethods()) app.listen(3000,()=>{ console.log('服务器已启动,端口正在监听...') })
4-koa 如何使用模板引擎
var koa=require('koa')
var app=new koa() var Router=require('koa-router') var router=Router() var path=require('path') var static=require('koa-static') app.use(static(path.join(__dirname,'public'))) var render=require('koa-art-template') render('app',{ root:path.join(__dirname,'views'), extname:'.html', debug:procress.env.NODE_ENV!=='productions' }) router.use('/',async(ctx)=>{ await ctx.render('apps',{ name:'张三' }) }) app.use(router.routes()) .use(router.allowedMethods()) app.listen(3000,()=>{ console.log('服务器已启动,端口正在监听...') })
5-使用 koa 实现一个用户增删改查的案
1. app.js
app.js为入口文件,功能是连接数据库,导入文件,引入koa组件,最后启动服务。
'use strict'
;
const fs = require(
'fs'
);
const path = require(
'path'
);
const mongoose = require(
'mongoose'
);
const db =
'mongodb://localhost/test'
;
/* 连接数据库 */
mongoose.Promise = require(
'bluebird'
);
mongoose.connect(db, {useMongoClient:
true
});
/**
* 获取数据库表对应的js对象所在的路径
* @type {[type]}
*/
const models_path = path.join(__dirname,
'/app/models'
);
/**
* 已递归的形式,读取models文件夹下的js模型文件,并require
* @param {[type]} modelPath [description]
* @return {[type]} [description]
*/
let walk =
function
(modelPath) {
fs.readdirSync(modelPath).forEach(
function
(file) {
let filePath = path.join(modelPath,
'/'
+ file)
let stat = fs.statSync(filePath)
if
(stat.isFile()) {
if
(/(.*)\.(js|coffee)/.test(file)) {
require(filePath)
}
}
else
if
(stat.isDirectory()) {
walk(filePath)
}
})
};
walk(models_path);
require(
'babel-register'
);
const Koa = require(
'koa'
);
const logger = require(
'koa-logger'
);
const session = require(
'koa-session'
);
const bodyParser = require(
'koa-bodyparser'
);
const app =
new
Koa();
app.use(logger());
app.use(session(app));
app.use(bodyParser());
/**
* 使用路由转发请求
* @type {[type]}
*/
const router = require(
'./config/router'
)();
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
console.log(
'app started at port 3000...'
);
2. 路由配置
路由配置在config/router.js中进行。
const Router = require(
'koa-router'
);
const User = require(
'../app/controllers/user'
);
module.exports =
function
() {
let router =
new
Router({
prefix:
'/api'
});
router.post(
'/test/user/users'
, User.users);
router.post(
'/test/user/user'
, User.user);
router.post(
'/test/user/add'
, User.addUser);
router.post(
'/test/user/delete'
, User.deleteUser);
return
router
};
post方法第一参数为路由地址,第二参数为路由地址对应的方法。
3. 表结构定义
表结构定义在app/models/user.js中。
let mongoose = require(
'mongoose'
);
let Schema = mongoose.Schema;
// 定义表结构
let UserSchema =
new
Schema({
name: {
type: String,
required:
true
},
sex: String,
area: String,
always: Boolean,
relationship: Array,
mobile: String,
phone: String,
desc: String,
id: String
});
// 参数User 数据库中的集合名称, 不存在会创建.
let User = mongoose.model(
'User'
, UserSchema);
module.exports = User;
4. 工具方法
一些增删改查的工具方法放在app/dbhelp/userHelp.js中
'use strict'
;
let mongoose = require(
'mongoose'
);
let User = mongoose.model(
'User'
);
/* 查找用户 */
exports.findAllUsers = async () => {
let query = User.find();
let res = [];
await query.exec(
function
(err, users) {
if
(err) {
res = [];
}
else
{
res = users;
}
});
return
res
};
/* 查找特定用户 */
exports.findFilterUsers = async (params) => {
let nameReg =
new
RegExp(params.name,
'i'
);
let query = User.find({
name: {
$regex: nameReg
}
});
let res = [];
await query.exec(
function
(err, users) {
if
(err) {
res = []
}
else
{
res = users;
}
});
return
res
};
/* 查找单个用户 */
exports.findUser = async (params) => {
let query = User.find({
id: params.id
});
let res = {};
await query.exec(
function
(err, tUser) {
if
(err) {
res =
'没有该用户'
;
}
else
{
res = tUser[0];
}
});
return
res
};
/* 新增用户 */
exports.addUser = async (user) => {
user = await user.save();
return
user
};
/* 编辑用户 */
exports.updateUser = async (user) => {
user = await User.update({id: user.id}, {
$set: {
name: user.name,
sex: user.sex,
area: user.area,
always: user.always,
relationship: user.relationship,
phone: user.phone,
mobile: user.mobile,
desc: user.desc
}
});
return
user
};
/* 删除用户 */
exports.deleteUser = async ({id}) => {
let flag =
false
;
console.log(
'flag==========>'
+ flag);
await User.remove({id},
function
(err) {
if
(err) {
flag =
false
}
else
{
flag =
true
}
});
console.log(
'flag=====await=====>'
+ flag);
return
flag
};
5. 路由配置中对应的方法
路由配置中对应的方法在app/controller/user.js中。
'use strict'
;
let xss = require(
'xss'
);
let mongoose = require(
'mongoose'
);
let User = mongoose.model(
'User'
);
let uuid = require(
'uuid'
);
import userHelper from
'../dbhelper/userHelper.js'
/* 多用户 */
exports.users = async (ctx, next) => {
let data;
if
(ctx.request.body) {
data = await userHelper.findFilterUsers(ctx.request.body)
}
else
{
data = await userHelper.findAllUsers()
}
ctx.body = {
success:
true
,
data
}
};
/* 单用户 */
exports.user = async (ctx, next) => {
let data = await userHelper.findUser(ctx.request.body)
ctx.body = {
success:
true
,
data
}
};
/* 添加(更新)用户 */
exports.addUser = async (ctx, next) => {
let newObj = ctx.request.body,
user2;
let id = newObj.id || uuid.v4();
let user =
new
User({
name: newObj.name,
sex: newObj.sex,
area: newObj.area,
always: newObj.always,
relationship: newObj.relationship,
phone: newObj.phone,
mobile: newObj.mobile,
desc: newObj.desc,
id: id
});
if
(newObj.id) {
user2 = await userHelper.updateUser(user);
}
else
{
user2 = await userHelper.addUser(user);
}
if
(user2) {
ctx.body = {
success:
true
,
data: user2
}
}
};
/* 删除用户 */
exports.deleteUser = async (ctx, next) => {
let id = xss(ctx.request.body.id);
let data = await userHelper.deleteUser({id});
ctx.body = {
success:
true
,
data
}
};