node.js学习笔记(二)

1.接受参数:get 和 post 

login.html

<form action="./login" method="get"><!--method=""-->
    <table>
        <tr>
            <td>姓名:</td>
            <td><input type="text" name="sex"/></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr>
            <td></td>
            <td><button type="submit">提交</button></td>
        </tr>
    </table>
</form>

router.js

var  url = require('url');//引用url
var  querystring  =  require('querystring');  //post需导入 
module.exports={//路由 login:function(req,res){ //----get方式接受参数---- var rdata = url.parse(req.url,true).query; console.log(rdata); if(rdata['sex']!=undefined){ console.log(rdata['sex']); console.log(rdata['password']); }; //-------post方式接收参数---------------- var post="";//定义了一个post变量,用于暂存请求体的信息; req.on('data',function(chunk){ post += chunk;//通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中; }); //-------注意异步------------- req.on('end',function(){//在end事件触发后,通过querystring.parse将post解析为真正的post请求格式,然后向客户端返回; post = querystring.parse(post); console.log('sex:'+post['sex']+' '); console.log('password:'+post['password']+' ') }); //采用闭包; recall = abc(req,res); readfile.readfile('./views/login.html',recall); } }
原文地址:https://www.cnblogs.com/qianmojing/p/6211296.html