本篇,我们介绍下 express中 body-parser 获取http请求体中的参数。
//01 express bodyParser 中间件 //介绍 body-parser 获取http请求体参数 // 1 npm install body-parser --save // // 2 var bodyParser = require('body-parser') // parse application/x-www-form-urlencoded // app.use(bodyParser.urlencoded({ extended: false })); var express=require('express'); var bodyParser = require('body-parser'); var app=express(); //配置body-parser中间件 // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()); app.get("/login",function (req,res) { res.send("<html><h3>用户登录</h3>" + "<form action='/login' method='post'> " + "用户名:<input type='text' name='username'/> <br/>"+ "密码:<input type='password' name='password'/> <br/>"+ "<input type='submit' value='登录' /> <br/>"+ "</form>"+ "</html>"); }); app.post("/login",function (req,res) { //获取post 请求体参数 var username =req.body['username']; var password =req.body['password']; if(username=='admin' && password=='123456'){ //登录成功 res.send("恭喜,登录成功"); }else{ res.send("登录失败"); } }); app.listen(3000);
ok !
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1