前台界面:
前台代码:
1 <form class="form-horizontal" method="post" action="http:127.0.0.1:3000/post"> 2 <div class="form-group"> 3 <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> 4 <div class="col-sm-4"> 5 <input type="text" name="username" class="form-control" id="inputEmail3"> 6 </div> 7 </div> 8 <div class="form-group"> 9 <label class="col-sm-2 control-label">性别</label> 10 <div class="col-sm-4"> 11 <label class="radio-inline"> 12 <input type="radio" name="sex" value="男" checked> 男 13 </label> 14 <label class="radio-inline"> 15 <input type="radio" name="sex" value="女"> 女 16 </label> 17 </div> 18 </div> 19 <div class="form-group"> 20 <label class="col-sm-2 control-label">爱好</label> 21 <div class="col-sm-4"> 22 <label class="checkbox-inline"> 23 <input type="checkbox" name="hobby" checked value="吃饭"> 吃饭 24 </label> 25 <label class="checkbox-inline"> 26 <input type="checkbox" name="hobby" value="睡觉"> 睡觉 27 </label> 28 <label class="checkbox-inline"> 29 <input type="checkbox" name="hobby" value="打豆豆"> 打豆豆 30 </label> 31 </div> 32 </div> 33 <div class="form-group"> 34 <div class="col-sm-offset-2 col-sm-10"> 35 <button type="submit" class="btn btn-default">提交</button> 36 </div> 37 </div> 38 </form>
node.js代码:
1 /** 2 * 原生node.js接收前台post请求数据 3 * @Author:Ghost 4 * @Date:2016/07/14 5 * @description: 6 * 1、引入http,querystring(字符串解析)模块 7 * 2、创建http服务器,监听3000端口 8 * 3、判断路由是否为post和请求类型是否为post,如果是则进入请求接收处理 9 * 4、声明变量alldata 存储接收到的数据 10 * 5、绑定http请求的data事件,接收存储数据字符串 11 * 6、绑定http请求的end事件,处理接收到的数据字符串,转换为对象 12 * 7、输出 13 */ 14 15 //引入模块 16 var http = require('http'); 17 var querystring = require('querystring'); 18 19 //创建服务器 20 var server = http.createServer(function (req, res) { 21 if (req.url === '/post' && req.method.toLowerCase() === 'post') { 22 var alldata = ''; 23 req.on('data', function (chunk) { 24 alldata += chunk; 25 }); 26 27 req.on('end', function () { 28 res.end('success'); 29 //将字符串转换位一个对象 30 console.log(alldata); //username=%E6%9D%8E%E5%9B%9B&sex=%E5%A5%B3&hobby=%E7%9D%A1%E8%A7%89&hobby=%E6%89%93%E8%B1%86%E8%B1%86 31 var dataString = alldata.toString(); 32 //将接收到的字符串转换位为json对象 33 var dataObj = querystring.parse(dataString); 34 //输出数据 35 console.log(dataObj); //{ username: '王五', sex: '男', hobby: [ '吃饭', '睡觉', '打豆豆' ] } 36 console.log(dataObj.username); //王五 37 console.log(dataObj.sex); //男 38 console.log(dataObj.hobby); //[ '吃饭', '睡觉', '打豆豆' ] 39 }); 40 }; 41 }); 42 //设置监听端口 43 server.listen(3000, "127.0.0.1", function () { 44 console.log("server is started listen port 3000"); 45 });