First, the installation: npm install body-parser
Second, loading: var bodyParser = require ( 'body-parser')
Third, the configuration: https://github.com/expressjs/body-parser
Call bodyParser.urlencoded ([options])
app.use(bodyParser.urlencoded({extended:true}))
Four, api.js get the data submitted by post req.body
var express = require('express')
var router = express.Router()
/**
* Unified interface format returns
*/
was the response data;
router.use((req,res,next)=>{
// Initialize the return data
responseData = {
code: 0, // error code is returned, the default is 0, 0 means no error
message: '', // error message. By default, no error is empty
}
/**
* [Not executed next, the program will be stuck here]
*/
next()
})
/**
* User Registration
* Registered Logic
*
* 1, user names, passwords can not be empty
* 2, are the same password twice
*
* 1, whether the user has been registered
* Database Query
*/
router.post('/user/register',(req,res,next)=>{
console.log(req.body)
// pass over the saved data into a variable
var username = req.body.username
var password = req.body.password
var repassword = req.body.repassword
// determine whether the user is empty
if(username == ''){
responseData.code = 1
responseData.message = 'user name can not be empty'
/**
* The data returned distal
* To json form
*/
res.json(responseData)
return
}
// determine whether the password is blank
if(password == ''){
responseData.code = 2
responseData.message = 'password is not blank'
res.json(responseData)
return
}
// determine whether the same password twice
if(password != repassword){
responseData.code = 3
responseData.message = 'Enter the password twice inconsistent'
res.json(responseData)
return
}
//registration success
responseData.message = 'registration success'
res.json(responseData)
})
module.exports = router