1、安装4个拓展(express、lodash、validator、body-parser)
npm intall express
npm intall lodash
npm intall validator
npm intall body-parser
2、新建route.js文件
const express = require('express')
const router = express.Router();
var validator = require('validator')
var isEmpty = require('lodash/isEmpty')
const validatorInput = (data) => {
let errors = {}
if(validator.isEmpty(data.username)){
errors.username = '用户名不能为空'
}
if(validator.isEmpty(data.password)){
errors.username = '密码不能为空'
}
if(validator.isEmail(data.email)){
errors.username = '邮箱不能为空'
}
if (!validator.equals(data.password, data.passwordConfirmation)){
errors.passwordConfirmation = '两次密码不一致'
}
return {
isValid: !isEmpty(errors),
errors
}
}
router.post("/register", (req, res) => {
const {isValid, errors} = validatorInput(req.body)
if (!isValid){
res.status(400).json(errors)
}else{
res.send({
msg: 'success'
})
}
})
module.exports = router
3、新建index.js文件
const express = require('express')
const app = express();
const router = require("./router")
const bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({
extended: true
}))
app.use('/api', router)
app.listen(3300, () => {
console.log('服务启动了(八点博客)')
})
4、运行index.js文件
node index.js
5、访问
http://localhost:3300/api/register