NodeJsExpress简单的用户注册登录和授权

1次阅读

共计 2322 个字符,预计需要花费 6 分钟才能阅读完成。

前言:
新建 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')
//jwt
const 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}}/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZGZiYWI1MDc3OTU4MTA0MDkyMjU4ZiIsImlhdCI6MTU5MTc1NDYxNX0.bg2JDwigQ5jYg-nOdNUENjJS80y1KmZySjZDhXpvmTM
正文完
 0