安装koa和创建项目
1.安装koa2
npm install koa@2 -g
2.创建项目
(1)安装koa2生成器
npm install koa-generator -g
(2)koa2生成一个test项目
koa2 demo_serve
cd demo_serve
npm install
npm run dev
使用koa2创建一个demo_serve服务端
在根目录下创建一个db文件夹用来写连接数据库的逻辑
db下新建一个index.js连接数据库
const mongoose = require('mongoose');
module.exports = () => {
// 连接数据库 本地数据库暂时模拟
// useNewUrlParser: true如果没有这数据库自动创建一个
mongoose
.connect('mongodb://localhost:27017/user', {
useNewUrlParser: true,
})
.then(() => {
console.log('数据库连接成功');
})
.catch((err) => {
console.log('数据库连接失败', err);
});
};
将db连接数据库引入到app.js文件中,进行调用,连接数据库
// 连接数据库
const mongoConnet = require('./db');
mongoConnet();
创建一个模型文件夹
models\index.js
const mongoose = require('mongoose');
// 系统用户的模型对象
const userSchema = new mongoose.Schema({
username: String,
password: String,
});
//users是一张自定义的数据库的表 专门存储数据
const User = mongoose.model('users', userSchema);
module.exports = {
User,
};
routes\index.js引入到app.js入口文件配置如下
app.js
const users = require('./routes/users');
app.use(users.routes(), users.allowedMethods());
1.简单版本数据库的增删改查简单的实现 routes\index.js文件里内容
const router = require('koa-router')();
const { User } = require('../models');
//这块相当于/users路由前缀
router.prefix('/users');
// 添加系统用户 http://localhost:3000/users/add
router.post('/add', async (ctx) => {
// 接收客户端的参数
// ctx.request.query 对应get请求 ctx.request.body对象 post请求
const { username = '', password = '' } = ctx.request.body;
console.log(username, password);
// 存到数据库
await User.create({ username, password })
.then((res) => {
if (res) {
console.log('添加成功');
// 返回值
ctx.body = {
code: 200,
message: '添加成功',
data: res,
};
} else {
// 返回值
ctx.body = {
code: 300,
message: '添加失败',
};
console.log('添加失败11');
}
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '服务器异常',
};
console.log('服务器异常', err);
});
});
//查詢系统用户 http://localhost:3000/users/find
router.post('/find', async (ctx) => {
// 查询全部数据
await User.find()
.then((res) => {
// 返回值
ctx.body = {
code: 200,
message: '查询成功',
data: res,
};
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '查询失败',
data: res,
};
});
});
//POST 查詢单个数据系统用户 http://localhost:3000/users/findOne
router.post('/findonePost', async (ctx) => {
const { id } = ctx.request.body;
// 查询全部数据
await User.findOne({ _id: id })
.then((res) => {
console.log(res);
// 返回值
ctx.body = {
code: 200,
message: '查询成功',
data: res,
};
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '查询失败',
data: res,
};
});
});
//get 查詢单个数据系统用户 http://localhost:3000/users/findoneGet/617d6ecbc8b5ed31ca6d6a8f
router.get('/findoneGet/:id', async (ctx) => {
const { id } = ctx.params;
// 查询全部数据
await User.findOne({ _id: id })
.then((res) => {
console.log(res);
// 返回值
ctx.body = {
code: 200,
message: '查询成功',
data: res,
};
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '查询失败',
data: res,
};
});
});
// 修改系统用户 http://localhost:3000/users/update
router.post('/update', async (ctx) => {
const { id, username, password } = ctx.request.body;
//update换成updateMany
await User.updateMany(
{ _id: id },
{
username,
password,
}
)
.then((res) => {
if (res) {
console.log('修改成功');
// 返回值
ctx.body = {
code: 200,
message: '修改失败',
data: res,
};
} else {
// 返回值
ctx.body = {
code: 300,
message: '修改失败',
};
console.log('修改失败11');
}
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '服务器异常',
};
console.log('服务器异常', err);
});
});
// 删除系统用户 http://localhost:3000/users/del
router.post('/del', async (ctx) => {
const { id } = ctx.request.body;
await User.findOneAndDelete({ id })
.then((res) => {
// 返回值
ctx.body = {
code: 200,
message: '删除成功',
data: res,
};
})
.catch((err) => {
// 返回值
ctx.body = {
code: 400,
message: '服务器异常',
};
console.log('服务器异常', err);
});
});
module.exports = router;
1.增强版本 controller\user.js内容
在根目录下新建一个 controller\user.js,将逻辑代码抽出优化
controller\user.js内容如下:
/*
当前文件为user接口系列的业务逻辑层
*/
const { User } = require('../models');
// 用户添加(post) http://localhost:3000/users/add
const userAdd = async (ctx) => {
// 接收客户端的参数
// ctx.request.query 对应get请求 ctx.request.body对象 post请求
const { username = '', password = '' } = ctx.request.body;
console.log(username, password);
// 存到数据库
await User.create({ username, password })
.then((res) => {
if (res) {
// 返回值
sucessCode(ctx, 200, '添加成功', res);
} else {
// 返回值
sucessCode(ctx, 300, '添加失败', res);
}
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
console.log('服务器异常', err);
});
};
// 用户删除(post) http://localhost:3000/users/del
const userDel = async (ctx) => {
const { id } = ctx.request.body;
await User.findOneAndDelete({ id })
.then((res) => {
// 返回值
sucessCode(ctx, 200, '删除成功', res);
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
});
};
// 用户修改(post) http://localhost:3000/users/update
const userUpdate = async (ctx) => {
const { id, username, password } = ctx.request.body;
//update换成updateMany
await User.updateMany(
{ _id: id },
{
username,
password,
}
)
.then((res) => {
if (res) {
console.log('修改成功');
// 返回值
sucessCode(ctx, 200, '修改失败', res);
} else {
// 返回值
sucessCode(ctx, 300, '修改失败', res);
console.log('修改失败11');
}
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
console.log('服务器异常', err);
});
};
// 用户查询-全部(post) http://localhost:3000/users/userFindAll
const userFindAll = async (ctx) => {
// 查询全部数据
await User.find()
.then((res) => {
// 返回值
sucessCode(ctx, 200, '查询成功', res);
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
});
};
// 用户查询-单个(post) http://localhost:3000/users/userFindOne
const userFindOne = async (ctx) => {
const { id } = ctx.request.body;
// 查询全部数据
await User.findOne({ _id: id })
.then((res) => {
console.log(res);
// 返回值
sucessCode(ctx, 200, '查询成功', res);
})
.catch((err) => {
// 返回值
errCode({}, 400, '服务器异常', {});
});
};
// 用户查询-单个(get) http://localhost:3000/users/userFindOneGet
const userFindOneGet = async (ctx) => {
const { id } = ctx.params;
// 查询全部数据
await User.findOne({ _id: id })
.then((res) => {
console.log(res);
// 返回值
sucessCode(ctx, 200, '查询成功', res);
})
.catch((err) => {
// 返回值
errCode({}, 400, '服务器异常', {});
});
};
// 请求成功编码处理
const sucessCode = (ctx, code, message, data) => {
ctx.body = {
code,
message,
data,
};
};
// 请求失败编码处理
const errCode = (ctx, code, message, data) => {
ctx.body = {
code,
message,
data,
};
};
// 导出函数
module.exports = {
userAdd,
userDel,
userUpdate,
userFindAll,
userFindOne,
userFindOneGet,
};
增强版routes\index.js文件里内容
const router = require('koa-router')();
const {
userAdd,
userDel,
userUpdate,
userFindAll,
userFindOne,
userFindOneGet,
} = require('../controller/user');
//这块相当于/users路由前缀
router.prefix('/users');
// 添加系统用户
router.post('/userAdd', userAdd);
// 删除系统用户
router.post('/userDel', userDel);
// 修改系统用户
router.post('/userUpdate', userUpdate);
//查詢系统用户
router.post('/userFindAll', userFindAll);
//POST 查詢单个数据系统用户
router.post('/userFindOne', userFindOne);
//get 查詢单个数据系统用户
router.get('/userFindOneGet/:id', userFindOneGet);
module.exports = router;
终极版 controller\crudUtil\index.js 内容
在controller新建 controller\crudUtil\index.js文件,将controller里的user.js的增删改查逻辑抽取出来进行封装
/*
封装增删改查代码
*/
// 新增数据
const add = (model, ctx, params) => {
const { username = '', password = '' } = params;
// 存到数据库
return model
.create({ username, password })
.then((res) => {
if (res) {
// 返回值
sucessCode(ctx, 200, '添加成功', res);
} else {
// 返回值
sucessCode(ctx, 300, '添加失败', res);
}
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
console.log('服务器异常', err);
});
};
// 删除数据
const deleteOne = (model, ctx, params) => {
const { id } = params;
return model
.findOneAndDelete({ id })
.then((res) => {
// 返回值
sucessCode(ctx, 200, '删除成功', res);
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
});
};
// 查数据-全部
const findAll = (model, ctx) =>
model
.find()
.then((res) => {
// 返回值
sucessCode(ctx, 200, '查询成功', res);
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
});
// 查数据-单个
const findOne = (model, ctx, id) =>
model
.findOne({ _id: id })
.then((res) => {
console.log(res);
// 返回值
sucessCode(ctx, 200, '查询成功', res);
})
.catch((err) => {
// 返回值
errCode({}, 400, '服务器异常', {});
});
// 修改
const update = (model, ctx, params) => {
const { id, username, password } = params;
return model
.updateMany(
{ _id: id },
{
username,
password,
}
)
.then((res) => {
if (res) {
console.log('修改成功');
// 返回值
sucessCode(ctx, 200, '修改成功', res);
} else {
// 返回值
sucessCode(ctx, 300, '修改失败', res);
console.log('修改失败11');
}
})
.catch((err) => {
// 返回值
errCode(ctx, 400, '服务器异常', err);
console.log('服务器异常', err);
});
};
// 请求成功编码处理
const sucessCode = (ctx, code, message, data) => {
ctx.body = {
code,
message,
data,
};
};
// 请求失败编码处理
const errCode = (ctx, code, message, data) => {
ctx.body = {
code,
message,
data,
};
};
module.exports = {
add,
deleteOne,
findAll,
update,
findOne,
};
终极版 routes\index.js文件内容
/*
当前文件为user接口系列的业务逻辑层
*/
const { User } = require('../models');
const { add, deleteOne, findAll, update, findOne } = require('./crudUtil');
// 用户添加(post) http://localhost:3000/users/add
const userAdd = async (ctx) => {
// 接收客户端的参数
// ctx.request.query 对应get请求 ctx.request.body对象 post请求
// 存到数据库
await add(User, ctx, ctx.request.body);
};
// 用户删除(post) http://localhost:3000/users/del
const userDel = async (ctx) => {
await deleteOne(User, ctx, ctx.request.body);
};
// 用户修改(post) http://localhost:3000/users/update
const userUpdate = async (ctx) => {
await update(User, ctx, ctx.request.body);
};
// 用户查询-全部(post) http://localhost:3000/users/userFindAll
const userFindAll = async (ctx) => {
// 查询全部数据
await findAll(User, ctx);
};
// 用户查询-单个(post) http://localhost:3000/users/userFindOne
const userFindOne = async (ctx) => {
const { id } = ctx.request.body;
await findOne(User, ctx, id);
};
// 用户查询-单个(get) http://localhost:3000/users/userFindOneGet
const userFindOneGet = async (ctx) => {
const { id } = ctx.params;
// 查询全部数据
await findOne(User, ctx, id);
};
// 导出函数
module.exports = {
userAdd,
userDel,
userUpdate,
userFindAll,
userFindOne,
userFindOneGet,
};