一、連接數(shù)據(jù)庫創(chuàng)建集合規(guī)則
首先安裝依賴 npm install express mongoose
1、連接數(shù)據(jù)庫
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/demo', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}).then(() => {
console.log("數(shù)據(jù)庫連接成功");
})
2、創(chuàng)建集合規(guī)則
const UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true // 表示唯一鍵
},
password: {
type: String
}
})
const User = mongoose.model('User', UserSchema)
二、注冊
1、安裝加密模塊npm install bcrypt,并修改集合規(guī)則
// 集合規(guī)則password添加set方法
password: {
type: String,
set(val) {
// 返回同步hash加密10次后的值
return bcrypt.hashSync(val, 10)
}
}
2、將json處理中間件放在接口最上方
// 使用express中間件處理json數(shù)據(jù)
app.use(express.json())
3、接口
// 注冊
app.post('/api/register', async (req, res) => {
const user = await User.create({
username: req.body.username,
password: req.body.password,
})
res.send(user)
})
4、注冊成功存入已加密的密碼
{
"_id": "606ac9909467de1ed008468c",
"username": "ceshiuser",
"password": "$2b$10$Py0lNdlY2JZOWBfC3wkk4OLIIzsdWoDRsID1z9jqPa9qO3ewVvD8a",
"__v": 0
}
三、登錄
1、安裝token模塊npm install jsonwebtoken
const jwt = require('jsonwebtoken')
const SECRET = ‘jasdkljaskldjASKDJASKLJDKL’
2、密碼驗(yàn)證生成token
// 登錄
app.post('/api/login', async (req, res) => {
const user = await User.findOne({
username: req.body.username
})
if (!user) {
return res.status(422).send({
msg: '用戶不存在'
})
}
// 比較傳過來的密碼和數(shù)據(jù)庫的密碼是否一樣,返回值為布爾值
const isPasswordValid = bcrypt.compareSync(req.body.password, user.password);
if (!isPasswordValid) {
return res.status(423).send({
msg: '密碼錯誤'
})
}
// 生成token
const token = jwt.sign({
id: String(user._id)
}, SECRET)
res.send({
user,
token
})
})
四、通過請求頭token獲取用戶信息
app.get('/api/profile', async (req, res) => {
if (!String(req.headers.authorization)) {
return res.status(425).send({
msg: 'token不存在'
})
}
// 獲取請求頭的token值
const getToken = String(req.headers.authorization).split(' ').pop();
// 解析出token
const { id } = jwt.verify(getToken, SECRET)
// 查詢用戶
const user = await User.findById(id)
res.send(user)
})
封裝中間件復(fù)用
const auth = async (req, res, next) => {
if (!String(req.headers.authorization)) {
return res.status(425).send({
msg: 'token不存在'
})
}
// 獲取請求頭的token值
const getToken = String(req.headers.authorization).split(' ').pop();
// 解析出token,解構(gòu)用戶id
const { id } = jwt.verify(getToken, SECRET)
// 查詢用戶信息
req.user = await User.findById(id)
next()
}
調(diào)用
app.get('/api/profile', auth, async (req, res) => {
res.send(req.user)
})