express+mongoose
登录注册步骤
1.安装express nodemon RSET Client
const express = require('express')
const app = express()
app.get('/', async(req,res)=?{
console.log('ok')
})
app.listen(3000,()=>{
console.log('http://localhost:3000')
})
2.RSET Client使用
@url=http://localhost:3000/api
@json=Content-Type: application/json
###
GET {{url}}
### 注册
POST {{url}}/register
{{json}}
{
"username":"zs",
"age":12
}
3.建立mongoDB连接,最好在models文件下操作db数据库,
models/db.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/express-auth')
module.exprots = mongoose
4.建立user模型
const db = require('./db');
const userSchema = db.Schema({
username: { type: String },
password: { type: String }
})
module.exports = db.model('User', userSchema, 'user')
5 使用express.json
app.use(express.json())
6.将项目的路由抽离出来,可以协作多人开发
app.use('/', require('./router/index.js'))
app.use('/api', require('./router/api.js'))
const express = require('express');
const router = express.Router()
router.get('/', (req, res) => {
res.send('首页')
})
module.exports = router
const express = require('express');
const router = express.Router()
router.use('/user', require('./api/user'))
module.exports = router
const express = require('express');
const router = express.Router()
router.post('/', (req, res) => {
res.send('登录xxxx啊')
})
module.exports = router
8.在user.js里写引入userModel.js(注册)
const express = require('express');
const userModel = require('../../models/userModel');
const router = express.Router()
router.post('/register', async (req, res) => {
const user = await userModel.create({
username: req.body.username,
password: req.body.password
})
res.send(user)
})
module.exports = router
@url=http://localhost:3000/api
@json=Content-Type: application/json
###
GET {{url}}
### 注册
POST {{url}}/user/register
{{json}}
{
"username":"zs",
"password":"123456"
}
7. 限定用户名唯一(注册)
mongoose.connect(dbUrl, (err) => {
if (err) {
console.log(err);
return
}
console.log('连接数据库成功');
}, { useCreateIndex: true })
const userSchema = new db.Schema({
username: {
type: String,
unique: true
},
password: { type: String }
})
8 在Schema中设置密码加密(注册)
password: {
type: String, set (val) {
return require('bcrypt').hashSync(val, 10)
}
}
9 开始写登陆接口
router.post('/login',async(req,res)=>{
const user = userModel.findOne({
username:req.body.username
})
if(!user){
return res.status(422).send({message:"用户名不存在"})
}
const passwordIsTrue = require('bcrypt').compareSync(req.body.username,user.password)
if(!passwordIsTrue){
return res.status(422).send({message:"用户名密码错误"})
}
const jwt = require('jsonwebtoken')
const token jwt.sign({id:user._id},key)
res.send({
token,
create_time:new Date(),
user
})
})
10 userInfo用户信息
router.get('/userInfo',async (req,res)=>{
const userToken = req.headers.authorization.split(' ').pop()
const IsTokenTrue = jwt.verify(userToken,key)
const {id} = IsTokenTrue
const data = awite userInfoModel.find({_id:id})
res.send(data)
})
提示
jwt.verify在校验的时候也会将引号也校验,注意...自己在代码里测试http的时候千万注意,翻车了一会.....
|