1:项目结构:
2:路由添加自定义验证规则
路由定义:
const express = require('express')
const checkAuth = require('../middlewares/authorization')
const router = express.Router()
const ApiController = require('../controllers/apiController')
const apiController = new ApiController()
/**
* 在这里定义路由
*/
//登陆注册路由
router.post('/users', checkAuth, apiController.userLogin.bind(apiController))
module.exports = router
这里的checkAuth就是对参数进行自定义验证,这里是对参数numbet(手机号码)做验证
const logger = require("log4js").getLogger("middlewares/authorization");
/**
*做一个检查,提前拦截错误的方法,加到路由地址的后边router.get('/:webinarId/online_audiences', checkAuth, webinarController.getOnlineAudienceList.bind(webinarController))
*自定义验证规则
* @param {*} next
*/
function checkParameter (req, res, next) {
console.log('*****自定义验证规则*****')
const number = req.body.number
const password = req.body.password
if (!number || number == "" || !password || password == "") {
return res.status(401).json({
msg: '请检验您的信息是否全部填写!'
})
}
const myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
if (!myreg.test(number)) {
return res.status(401).json({
msg: '请输入正确的手机号码!'
})
}
next()
}
module.exports = checkParameter;
3:请求示例:
1: number或者password为空的情况下:
2:手机号码格式输入不正确的情况下:
![]()
4:demo地址
GitHub地址
https://github.com/liudandandear/Express-apidemo