server.js
const express = require('express')
const app = express()
const jwt = require('jsonwebtoken')
app.use(express.json())
const SECRET = 'adgfdvxchrhetwafasc'
const { User } = require('./models')
//查数据
app.get('/api/users', async(req, res) => {
const users = await User.find()
res.send(users)
})
//注册
app.post('/api/register', async(req, res) => {
// console.log(req.body)
const user = await User.create({
username: req.body.username,
password: req.body.password
})
res.send(user)
})
// 登录
app.post('/api/login', async(req, res) => {
const user = await User.findOne({
username: req.body.username
})
if (!user) {
return res.status(422).send({
message: '用户名不存在yo'
})
}
//密码校验
const isPasswordValid = require('bcrypt').
compareSync(
req.body.password,
user.password
)
if (!isPasswordValid) {
return res.status(422).send({
message: '密码错误yo'
})
}
//生成token
const token = jwt.sign({
id: String(user._id) //可能是对象类型,需要强转
}, SECRET)
res.send({ user, token })
})
const auth = async(req, res, next) =>
const raw = await String(req.headers.authorization).split(' ').pop()
//验证解密
const { id } = jwt.verify(raw, SECRET)
req.user = await User.findById(id)
next()
}
//获取token
app.get('/api/profile', auth, async(req, res) => {
// console.log(String(req.headers.authorization).split(' ').pop());
res.send(req.user)
})
//开启服务器
app.listen(4005, () => {
console.log('http://localhost:4005');
})
models.js
const mongoose = require('mongoose')
//连接数据库
mongoose.connect('mongodb://localhost:27017/express_auth', {
useNewUrlParser: true,
useCreateIndex: 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)
//删除数据
// User.db.dropCollection('users')
//导出的是对象,导入的也是对象
module.exports = { User }
VsCode中有一个好用的插件,Rest Client
无需切换窗口,测试,调试,代码编辑都在一个 VSCode 中完成
test.http
@url = http://localhost:4005/api
@json = Content-Type: application/json
###
GET {{url}}/users
###注册
POST {{url}}/register
{{json}}
{
"username":"wzy",
"password":"123456"
}
###登录
post {{url}}/login
{{json}}
{
"username":"wzy",
"password":"123456"
}
###个人信息
get {{url}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlNzJlMzU1ZTkyNGI1MTZhMGY1Y2M2NCIsImlhdCI6MTU4NDU5MTg1MX0.ZR8IbU9WP4DMnaNk6TkKrihNwPnqNnr58IbyM7e2rBc