使用data和end事件來獲取post數據,
相關閱讀:http://www.linuxidc.com/Linux/2012-02/53535.htm 與 http://www.linuxidc.com/Linux/2012-02/53536.htm
代碼如下:
[javascript]
- var http = require('http');
- var server = http.createServer();
- var querystring = require('querystring');
- var firstPage = function(res){
- res.writeHead(200, {'Content-Type': 'text/html'});
- var html = '<html><body>'+
- '<form action="/login" method="post">'+
- 'name:<input type="text" name="name"> </br>'+
- 'password:<input type="password" name="pwd"></br>'+
- '<input type="submit" value="login">'+
- '</form>'+
- '</body></html>';
- res.end(html);
- }
-
- var login = function(req, res) {
- var info ='';
- req.addListener('data', function(chunk){
- info += chunk;
- })
- .addListener('end', function(){
- info = querystring.parse(info);
- if(info.name == 'a' && info.pwd =='1'){
- res.end('login success ' + info.name);
- }else{
- res.end('login failed ' + info.name);
- }
- })
- }
-
- var requestFunction = function (req, res){
- if(req.url == '/'){
- return firstPage(res);
- }
- if(req.url == '/login'){
- if (req.method != 'POST'){
- return;
- }
- return login(req, res)
- }
- }
-
- server.on('request',requestFunction);
- server.listen(1337, "127.0.0.1");
-
- console.log('Server running at http://127.0.0.1:1337/');
以上代碼實現了一個登錄驗證用戶,將以上代碼保存到 example4.js
cmd鍵入 node example4.js
浏覽器地址欄鍵入 http://127.0.0.1:1337/
如果輸入name:a password:1 點擊login
如果輸入name:a password:2 點擊login
該例子 from使用的是默認的application/x-www-form-urlencoded.