Item 1: post request to obtain the server response data into the database and presented;
demand:
achieve:
1) project directory structure
2) the server code:
Express the require = const ( 'Express' ); // introducing user router const = userRouter the require ( './ Routers / user.js' ); // introduced to third intermediate const = bodyParser the require ( 'body-Parser' ); // create a web server var server = Express (); server.listen ( 3001 ); // hosting static resources to the public directory ister.html server.use (express.static ( 'public' )); // use middleware post body-parser parses the request data object server. use (bodyParser.urlencoded ({ extended:false })); // the user to mount the router / User server.use ( '/ User', userRouter);
3) router Code
// introduced mysql connection pool object const = the require the pool ( '../ pool.js' ); Express const = the require ( 'Express' ); // Create an empty router var Router = express.Router (); // add routes // 1, user registration router.post ( '/ register', ( req, res) => { // Get the requested data post var obj = req.body; console.log(obj); // if the username is empty var $ = the uname obj.uname; IF (! $ The uname) { res.send ({code: 401, MSG: 'The requires the uname' }); // stop execution continues back return ; } // determines whether the password is empty var $ upwd = obj.upwd; IF (! $ Upwd) { res.send({code:402,msg:'upwd requires'}); return; } // determines whether the mailbox is empty var $ = In Email obj.email; IF (! $ In Email) { res.send({code:403,msg:'email requires'}); return; } // determines whether the phone is empty var $ Phone = obj.phone; IF (! $ Phone) { res.send({code:404,msg:'phone requires'}); return; } // perform sql statement, the register data into the data table xz_user, a successful response code {: 200 is, MSG: "Register SUC"} pool.query ( "INSERT INTO DEMP (the uname, upwd, In Email, Phone) values ( ????,,,) ", [obj.uname, obj.upwd, obj.email, obj.phone], (ERR, Result) => { IF (ERR) the throw ERR; console.log(result); }); res.send ( 'registered successfully' ); }); // Export module.exports = router;
4) Connection Pool Code
the require MySQL = const ( 'MySQL' ); // create a connection pool object var the pool = mysql.createPool ({ host:'127.0.0.1', port:'3306', user:'****', password:'****', database:'xz', connectionLimit:20 }); // derived connection pool object module.exports = pool;
5) front-end code
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="/user/register" method="post"> 用户:<input type="text" name="uname"><br> 密码:<input type="text" name="upwd"><< E-mail:>brinput type="text" name="email"><br> 手机:<input type="text" name="phone"><br> <input type="submit"> </form> </body> </html>