Node.js_常用的模块(四)

2020-02-26  本文已影响0人  learninginto

Node.js_常用的模块(四)

主要介绍几个模块:url / querystring / path / process / crypto

一、url字符串

二、querystring查询字符串

三、path路径

四、process

五、crypto加密

crypto模块提供了加密功能,包括对 OpenSSL 的哈希、HMAC、加密、解密、签名、以及验证功能的一整套封装。

  1. 引入crypto模块

    const crypto = require("crypto")
    
  2. 创建加密方式(以sha256为例)

    const hash = crypto.createHash("sha256");
    
  3. 加密需要加密的数据

    hash.update(password);
    
  4. 获取到要加密的数据

    console.log(hash.digest('hex'));
    

    因为只用一次,通常直接放到插入语句中,以用户注册为例:

    
    const userModel = require("../model/user");
    const crypto = require('crypto');
    
    const register = async (req, res) => {
        const { username, password } = req.body;
    
        let data = await userModel.userFindOne({ username });
        if (!data) {
            //1、加密 创建加密方式
            const hash = crypto.createHash('sha256');
            //2、加密 需要加密的数据
            hash.update(password);
            //3、获取到加密的数据
            //console.log(hash.digest('hex'))
            let data = await userModel.userSave({ username, password: hash.digest('hex') });
            // console.log(data)
            res.json({
                code: 200,
                errMsg: "",
                data: {
                    info: "注册成功",
                    code: 1
                }
            })
    
        } else {
            res.json({
                code: 200,
                errMsg: "",
                data: {
                    info: "用户名重复",
                    code: 0
                }
            })
        }
    }
    
    module.exports = {
        register
    }
    
上一篇 下一篇

猜你喜欢

热点阅读