前言:
新建node-auth文件夹,新建server.js文件,初始化文件夹 npm init -y
(git init)
1.安装express, mongoose,rest-client
2.开启服务器const express = require('express)
const app = express()
//连接数据库require('./modles/db')
//jwtconst jwt = require('jsonwebtoken')
app.use(express.json())
//密钥const SECRET = 'sajkFAjscbhsafchdsvjkks';app.get('/api', async(req, res) => { const user = await User.find(); res.send(user); // res.send('ok');})//注册app.post('/api/register', async(req, res) => { const user = await User.create({ username: req.body.username, password: req.body.password }) res.send(user); // console.log(req.body);});//登录app.post('/api/login', async(req, res) => { const user = await User.findOne({ username: req.body.username }); if (!user) { return res.status(422).send({ message: '用户名不存在' }) } //验证密码 compareSync const isPasswordValid = require('bcryptjs').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 }) // res.send(isPasswordValid); // res.send(user);});// 中间件const auth = async(req, res, next) => {//获取token 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.listen(3000, () => {` console.log('listening port 3000!');})
3.连接数据库
/*ps:var bcrypt = require('bcryptjs');生成var salt = bcrypt.genSaltSync(10);var hash = bcrypt.hashSync("....", salt);//比较bcrypt.compareSync("....", hash); //一步到位var hash = bcrypt.hashSync('...', 8);*/const mongoose = require('mongoose')mongoose.connect('mongodb://localhost:27017/database', { new useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true})const userSchema = new mongoose.Schema({ username: { type: String, //唯一性 unique: true }, password: { type: String, // 加密bcrypt set(val) { return require('bcryptjs').hashSync(val, 10); } }})const User = mongoose.model('User', userSchema)module.exports = {User}
4.新建test.http (类似于postman)
@url=http://localhost:3001/api@json= Content-Type: application/json###get {{url}}### 注册post {{url}}/register{{json}}{ "username": "admin4", "password": "1234568"}### 登录post {{url}}/login{{json}}{ "username": "admin2", "password": "1234568"}### 个人信息get {{url}}/profileAuthorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZGZiYWI1MDc3OTU4MTA0MDkyMjU4ZiIsImlhdCI6MTU5MTc1NDYxNX0.bg2JDwigQ5jYg-nOdNUENjJS80y1KmZySjZDhXpvmTM