node中介軟體
阿新 • • 發佈:2020-07-23
npm i body-parser
post 請求主題中介軟體
constbodyParser=require('body-parser')const bodyParser = require('body-parser') // 建立 application/json 解析 const jsonParser = bodyParser.json() app.use(jsonParser)
express-validator 表單校驗中介軟體
const { body } = require('express-validator'); const UserModel = require('../model/User') const bcryptView Code= require('bcrypt') /** * 使用者註冊資料校驗 * */ exports.addUserValidate = [ // name 不為空 string body('name').notEmpty().isString().withMessage('name欄位不能為空且必須是string型別'), //withMessage配置可有可無 // password 不為空 string body('password').notEmpty().isString().withMessage('password欄位不能為空格且必須是string型別'), // 年齡數字 不為空 0<=age<=100body('age').notEmpty().isInt(), //isInt number型別驗證失效 // userId欄位資料資料庫唯一 不為空 且為string body('userId').notEmpty().isString().custom(value => { return UserModel.findOne({ userId: value }).then(user => { if (user) { return Promise.reject('userId 已存在'); } }); }) ]/** * 使用者登入資料校驗 * */ let currentUser = null //用於儲存當前 exports.userLoginValidate = [ body('userId').notEmpty().isString().custom(value => { return UserModel.findOne({ userId: value }).select('+password').then(user => { // 判斷使用者是否存在 if (!user) { return Promise.reject('該使用者id尚未註冊'); } currentUser = user }); }), body('password').notEmpty().isString().custom(async value => { const match = await bcrypt.compare(value, currentUser.password); // 明文 ,加密密碼 if (!match) return Promise.reject('祕密輸入有誤,請再輸入一次'); }), ]