node.js 常用模块、中间件

117 阅读2分钟

ORM模块

Sequelize

跨域

CORS 中间件

安装:

npm install cors

使用:

var express = require('express')
var cors = require('cors')
var app = express()
 
// 添加全局中间件
app.use(cors())

鉴权

jsonwebtoken 模块-生成token

安装:

npm install jsonwebtoken

使用:

const jwt = require("jsonwebtoken");

// 加密盐
const secretKey = "salt @#$ key";

// 用户信息
const data = { username: "root" };

const token = jwt.sign(data, secretKey);

更多请查看官网,转载于github:github.com/auth0/node-…


express-jwt 中间件-解析token

安装:

npm install jsonwebtoken

使用:

const { expressjwt } = require("express-jwt");

// 秘钥
const secret = "shhhhhhared-secret";

app.get(
  "/protected",
  expressjwt({ secret , algorithms: ["HS256"] })
   //unless 用于排除不需要鉴权的地址
  .unless({path:["/api/getToken"]}),
  function (req, res) {
     // 鉴权成功后会将解析出来的用户信息添加到req.auth里
    if (!req.auth.admin) return res.sendStatus(401);
    res.sendStatus(200);
  }
);

更多请查看官网,转载于github:github.com/auth0/expre…


参数解析 中间件

multer 中间件

用于处理 multipart/form-data 类型的表单数据,它主要用于上传文件。

安装:

npm nstall multer

使用:

const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file 是 `avatar` 文件的信息
  // req.body 将具有文本域数据,如果存在的话
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files 是 `photos` 文件数组的信息
  // req.body 将具有文本域数据,如果存在的话
})

const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files 是一个对象 (String -> Array) 键是文件名,值是文件数组
  //
  // 例如:
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body 将具有文本域数据,如果存在的话
})

如果你需要处理一个只有文本域的表单,你应当使用 .none():

const express = require('express')
const app = express()
const multer  = require('multer')
const upload = multer()

app.post('/profile', upload.none(), function (req, res, next) {
  // req.body 包含文本域
})

更多请查看官网,转载于github:github.com/expressjs/m…


加密

bcrypt 模块

安装:

// 安装依赖
npm install node-gyp

// 安装bcrypt
npm install bcrypt

使用:

// -----同步加密和验证-----
const bcrypt = require("bcrypt")
//  生成salt的迭代次数 
const saltRounds = 10; 
//  生成随机salt字符串 
const salt = bcrypt.genSaltSync(saltRounds); 
//  获取hash值 ,第一个参数为密码,第二个为加密盐
const hashPassword = bcrypt.hashSync("123456", salt);
//  验证比对,返回布尔值表示验证结果 true表示一致,false表示不一致 
const result = bcrypt.compareSync('123456', hashPassword)


// -----异步加密和验证----- 
//  生成随机salt字符串 
bcrypt.genSalt(10, (err, salt) => { 
    //  对明文加密 
    bcrypt.hash('123456', salt, (err, hashPassword) => {
        console.log(hashPassword) 
        //  验证 
        bcrypt.compare('123456', pwd, (err, result) => {
            console.log(result) 
        }) 
    }) 
})