// 继续上次写的基础上,增加了一些东西,也就是一些用koa书写的功能
// 因为koa主要是用于写一些自己需要的一些借口,所以必备的就是登录和注册
// 所以我们现在就在上一篇文章(本人主页第一个作品)的基础上在增加登录注册
1.注册需要用到post请求来添加而且我们现在也需要一个数据库来储存我们的数据,所以我们要先安装一个软件,MongoDB Compass2,用这个软件来存储数据
链接数据库
1.打开MongoDB Compass2复制里面的地址
// 下载 npm i mongoose
2.在koa文件根目录中创建config.js,把复制的地址这样的写入config.js
module.exports = {
connectionStr:
"mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"
};
3.开始连接数据库,这句话写到app.js中,执行,如果连接成功就会提示连接成功
//连接接数据库
mongoose.connect(db,{ useNewUrlParser: true })
.then(() =>{
console.log('mongodb数据库连接成功')
}).catch(err =>{
console.log('连接错误'+err)
})
// 数据库连接之后,我们就可以注册账号存到数据库把数据
注册功能
// 要写注册功能需要先来写一个用户模型
1.创建文件./modeles/userSchema.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//实例化一个数据模板
const UserSchema = new Schema({
name: { type: String, required: true }, //type数据类型。 required是否不能为空
email: { type: String, required: true },
password: { type: String, required: true },
date: { type: Date, default: Date.now }, //default默认值, Date.now当前时间
});
module.exports = mongoose.model("Users", UserSchema);//User指的是当前存储的名称
2.接收post发送过来的数据需要下载东西
//npm install koa-body -S. 用来接收页面发送过来的东西
3.都结束之后可以写一个案例应用一下
./router/user.js
const Router = require("koa-router");
const router = new Router({ prefix: "/users" }); //定义一个就是进入页面的二级的一个前缀
const User = require("../modules/userSchema.js");
router.get("/", (ctx) => {
ctx.body = { name: "tanwei" }; //返回值
});
router.post("/reg", async (ctx) => { //post请求
const { name, email, password } = ctx.request.body; //结构请求借口的时候请求 过来的数据
//存储到数据库
const findResult = await User.find({ email: ctx.request.body.email });
if (findResult.length > 0) {
ctx.body = { msg: "邮箱已经存在!!!" };
} else {
//没查到
const newUser = new User({
name: ctx.request.body.name,
email: ctx.request.body.email,
password: ctx.request.body.password,
});
//存储到数据库
await newUser
.save()
.then((res) => {
ctx.body = {status:200,msg:"注册成功"}
})
.catch((err) => {
console.log(err);
});
}
});
module.exports = router;
登录功能
// 因为已经写完了注册功能,所以写登录功能也会非常的简单,逻辑是差不多的,只不过登录是在数据库中查找你要登陆的账号,然后验证密码输入是否正确
1.直接写案例即可
//跟注册写在一起就可以,写在注册下面
// 登录接口
router.post("/login", async (ctx) => {
let { name, password, cade } = ctx.request.body;
const findResult = await User.find({ name }); //在数据库中查找名字和你在页面输入一样的名字的数据
if (findResult.length > 0) {
//判断是否找到
if (
findResult[0].name === name &&
isRightPw(password, findResult[0].password)
) {
ctx.body = { status: 200, msg: "登录成功!", token: token };
} else {
ctx.body = { status: 401, msg: "账号或密码错误!!" };
}
} else {
ctx.body = { status: 401, msg: "用户不存在!" };
}
});
这样登录注册就已经写完,然后看的时候如果发现什么地方写的有问题欢迎留言私信!!!