第一步 安装模块
> npm install express --save // 服务框架
> npm install bcrypt@5.0.0 --save // 用于密码加密
> npm install jsonwebtoken --save // 用于生成token
> npm install body-parser --save // 用于获取post 方式提交参数
> npm install mongoose --save // 用于在node中操作MongoDB数据库
第二步 连接mongoDB数据库创建模式
/*
* @Author: 龙猫不热
* @Date: 2021-08-31 14:07:10
* @LastEditTime: 2021-09-01 16:48:35
* @LastEditors: your name
* @FilePath: \text\Node-API\db.js
*/
const mongoose = require('mongoose');
const db = mongoose.connection;
mongoose.connect('mongodb://localhost:27017/test');
db.on('error', function () {
console.error.bind(console, 'connection error:');
});
db.once('open', function () {
console.log('mongoDB-连接成功');
});
const accountSchema = mongoose.Schema({
userName: { type: String, require: true, unique:true},
password: { type: String, require: true }
});
const accountModel = mongoose.model('account', accountSchema);
module.exports = {
accountModel
};
第三步 编写路由
/*
* @Author: 龙猫不热
* @Date: 2021-09-01 14:11:26
* @LastEditTime: 2021-09-02 14:50:33
* @LastEditors: your name
* @FilePath: \text\Node-API\router\account.js
*/
const express = require("express");
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { accountModel, userModel } = require("../db");
const router = express.Router();
const saltRounds = 10;
const privateKey = "long-mao-bu-re";
router.post('/login', (req, res) => {
if (req.body.userName && req.body.password) {
console.log(req.body);
const { userName, password } = req.body;
accountModel.findOne({ userName }).then(doc => {
console.log(doc);
let isMyPass = bcrypt.compareSync(password, doc.password);
console.log(isMyPass);
if (isMyPass) {
let token = jwt.sign({ name: doc.userName }, privateKey);
res.setHeader('Authorization', `token ${token}`);
res.send({ status: 200, data: '登陆成功', token });
} else {
res.send({ status: 500, data: '密码错误' });
}
}).catch(err => {
res.send({ status: 500, data: '用户名不存在', err });
});
} else {
res.send({ status: 422, data: "参数不正确" });
}
});
router.post('/register', (req, res) => {
if (req.body.userName && req.body.password) {
const { userName, password } = req.body;
const hash = bcrypt.hashSync(password, saltRounds);
console.log(hash);
accountModel.create({ userName, password: hash }).then(result => {
res.send({ status: 200, data: [], message: "注册成功" });
console.log(result);
}).catch(err => {
res.send({ status: 500, data: [], message: "注册失败", err });
});
} else {
res.send({ status: 422, data: "参数错误" });
}
});
router.get("/list", (req, res) => {
const token = req.headers.authorization.split(" ").pop();
let isToken = jwt.verify(token, privateKey);
if (isToken) {
// res.send(token);
if (isToken.name !== "龙猫不热") {
res.send({ status: 403, data: [], message: '权限不足' });
} else {
userModel.find().then(doc => {
res.send({ status: 200, data: doc });
}).catch(err => {
res.send({status:403,data:err})
})
}
} else {
res.send({ status: 403, data: [], message: '身份验证失败' });
}
});
module.exports = router;
第四步 入口使用
/*
* @Author: 龙猫不热
* @Date: 2021-08-31 14:14:15
* @LastEditTime: 2021-09-01 14:19:20
* @LastEditors: your name
* @FilePath: \text\Node-API\app.js
*/
const express = require('express');
const accountRouter = require('./router/account');
const parse = require('body-parser');
const app = express();
const port = 3000;
app.use(parse.urlencoded({ extended: false }));
app.use(parse.json());
app.use('/user',accountRouter)
app.listen(port, () => {
console.log('server is running...');
});