三个文件:server.js定义api服务,models.js定义模型数据库操作,test.http是REST CLIENT插件的文件
server.js
const { User } = require('./models')
const express = require('express')
const jwt = require('jsonwebtoken')
const app = express()
const SECRET = 'fdafdasfasdofdasa'
app.use(express.json())
// User.db.dropDatabase()
// 获取所有用户
app.get('/api/users', async (req, res) => {
const users = await User.find()
res.send(users)
})
// 用户注册返回注册信息
app.post('/api/register', async (req, res) => {
const user = await User.create({
username: req.body.username,
password: req.body.password
})
res.send(user)
})
// 用户登录返回token
app.post('/api/login', async (req, res) => {
const user = await User.findOne({
username: req.body.username
})
if (!user) {
return res.status(422).send({
message: '用户名不存在'
})
}
const isPasswordValid = require('bcrypt').compareSync(
req.body.password,
user.password
)
if (!isPasswordValid) {
return res.status(422).send({
message: '密码无效'
})
}
// 生成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()
const { id } = jwt.verify(raw, SECRET)
req.user = await User.findById(id)
next()
}
// 获取用户信息
app.get('/api/profile', auth, async (req, res) => {
res.send(req.user)
})
// 获取用户的订单
app.get('/api/orders', auth, async (req, res) => {
const orders = await Order.find().where({
user: req.user
})
res.send(orders)
})
app.listen(3001, () => {
console.log('http://localhost:3001')
})
models.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/express-auth', {
useNewUrlParser: true
})
const UserSchema = new mongoose.Schema({
username: { type: String, unique: true},
password: {
type: String,
set ( val ) {
// 给密码加密
return require('bcrypt').hashSync(val, 10)
}
}
})
const User = mongoose.model('User', UserSchema)
module.exports = { User }
test.http
@url=http://localhost:3001/api
@json=Content-Type: application/json
### 所有用户
get {{url}}/users
### 注册
post {{url}}/register
{{json}}
{
"username": "user3",
"password": "123456"
}
### 登录
post {{url}}/login
{{json}}
{
"username": "user3",
"password": "123456"
}
### 个人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYxM2UxOTJlNDg4MzRkYzhkNTE4NWYzNyIsImlhdCI6MTYzMTQ2MDUwOH0.Jat8OBXwnGRBTtgLoJb0t-VzZAoRxYw9_6hrffIcNxU
最新回复