models.js內容
const mongoose = require("mongoose")
mongoose.connect('mongodb://localhost:27017/express-test',{//連接資料庫
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
const Userscheme = new mongoose.Schema({
username: { type: String , unique: true},//保證用戶名唯一
password: {
type: String,
set(val) {
return require('bcryptjs').hashSync(val,4)//對密碼加密
}
},
})
const User = mongoose.model('User', Userscheme)
//User.db.dropCollection('users')
module.exports = { User }//對外提供一個介面
server.js
const { User } = require('./models.js')//引入外部介面
const express = require("express")
const jwt = require('jsonwebtoken')//引入JWT用于身份驗證
const app = express()
const SECRET = 'zzkya'//jwt密鑰
app.use(express.json())
app.get('/api/users', async function(req, res) {//獲取用戶串列的所有用戶資訊
const users = await User.find()
res.send(users)
})
app.post('/api/register', async function(req, res) {//用戶注冊
const user = await User.create({
username: req.body.username,
password: req.body.password,
})
res.send(user)
})
app.post('/api/login', async function(req, res) {//用戶登錄
const user = await User.findOne({//檢驗用戶名
username: req.body.username
})
if(!user) {
return res.status(422).send({
msg:" 用戶名不存在"
})
}
const ispassword = require('bcryptjs').compareSync(//檢驗密碼
req.body.password,
user.password
)
if(!ispassword) {
return res.status(422).send({
msg:" 密碼錯誤"
})
}
//JWT通過用戶id和密鑰生成token
const token = jwt.sign({
id: String(user._id),
}, SECRET)
res.send({
user,
token: token
})
})
const auth = async (req, res, next) => {//中間件
const raw = String(req.headers.authorization).split(' ').pop()//獲取token
const { id } = jwt.verify(raw, SECRET)//驗證token回傳id
req.user = await User.findById(id)//通過id找到用戶
next()
}
app.get('/api/profile', auth, async function(req,res) {//使用中間件獲取用戶資訊
res.send(req.user)
})
app.listen(3030, () => {
console.log('ok!');
});
本次借助vscode的rest client來測驗
test.http
@url=http://localhost:3030/api
@json=Content-Type: application/json
###所有用戶
get {{url}}/users
###注冊
post {{url}}/register
{{json}}
{
"username": "zzk",
"password": "123"
}
###登錄
post {{url}}/login
{{json}}
{
"username": "zzk",
"password": "123"
}
###個人資訊
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmYTNmYTA3YTQzZWJiNDg3ODFkZmRiMiIsImlhdCI6MTYwNDU4MTg5Nn0.RJpgYSUHsfQSlqDv-eKtw8nWRi7tusHCCBeae1e8u3U
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/205286.html
標籤:其他
上一篇:谷歌華為布局Filecoin技術,共識性越強,FIL幣價上千破萬是必然
下一篇:共享汽車管理系統設計軟便件研究
