nodejs简易httpserver搭建--注册登录

用户注册登录

定接口

/*注册*/
/user?act=reg&name=aaa&pass=123
{"ok":"false","msg"="失败原因"} 
/*登录*/
/user?act=login&name=aaa&pass=123
{"ok":"false","msg"="失败原因"} 

访问方式

  • 访问文件
    • 例如:http:localhost:8080/1.html
  • 访问接口
    • 例如:http:localhost:8080//user?act=reg&name=aaa&pass=123

例子代码

const http = require('http');
const urlLib = require('url');
const fs = require('fs');
const querystring = require('qureystring');
var users = { "aaa": "123", "bbb": "456" };
var server = http.createServer(function (req, res) {
    //解析数据    
    var str = "";    
    req.on('data', function (data) {
            str += data;   
    });    
    req.on('end', function () { 
           var obj = libLib.parse(req.url, true);
           const url = obj.pathname;        
           const GET = obj.query;       
           const POST = querystring.parse(str);
        //区分接口文件        
        if (url == "/user") {  
           switch (GET.act) {    
                  case 'reg':        //检查用户是否存在             
                    if (users[GET.user]) {  
                        res.write('{"ok":false,"msg":"该用户已注册"}'
                    } else {//简易                        
                         users[GET.user] = GET.pass;                        
                         res.write('{"ok":true,"msg":"注册成功"}')                    
                    }                
                   case 'login':                    //检查用户是否存在,密码是否正确                    
                     if (users[GET.user]==null) {                
                          res.write('{"ok":false,"msg":"该用户未注册"}');                   
                        } else if (users[GET.user] != GET.pass) {             
                                   res.write('{"ok":false,"msg":"用户名或密码错误"}');                   
                        } else {               
                                  res.write('{"ok":true,"msg":"登录成功"}')          
                        }                
                   default:          
                                res.write('{"ok":false,"msg":"未知act"}');           
            }  
                       res.end();   
          } else {       
               //读取文件返回        
                var fileName = "./www" + url;            
                fs.readFile(fileName, function (data, err) {      
                          if (err) {            
                                  res.write('404');               
                          } else {          
                                    res.write(data);                
                         }            
               });      
          }
    });
});server.listen(8080);

HTML

<!DOCTYPE html>
<html lang="en"><head>   
 <meta charset="UTF-8">    
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title></head><body>    
 <form id="myfrom" onsubmit="return false;">       
      用户:<input type="text" id="user" name="user" ><br>  
      密码:<input type="password" id="pass" name="pass"><br>       
     <input type="button"  value="注册" id="regbnt">       
     <input type="button"  value="登录" id="loginbnt">   
</form>    
<script>        
      var regBnt = document.getElementById('regbnt');      
      var subBnt = document.getElementById('loginbnt');              
      function register(){ 
             const name =document.getElementById('user');        
             const pass = document.getElementById('pass');            
             var xhr = new XMLHttpRequest();            
             xhr.open('get', "http://localhost:8080/user?act=reg&user="+name.value+"&pass="+pass.value, false);            
             xhr.onreadystatechange = function(e) {  
                            if(xhr.readyState==4){         
                                       if((this.status >= 200 && this.status < 300) || this.status == 304){                    //alert(this.responseText);             
                                          var json= JSON.parse(this.responseText);                    
                                          console.log(json);                    
                                          if(json.ok){               
                                                   alert("注册成功");               
                                          }else{           
                                                  alert('注册失败:'+json.msg);       
                                          }               
                            }else{            
                                    alert("通信错误!");          
                                          }         
                                     };    
                            }           
                             xhr.send(null); 
   }        
   regBnt.onclick = function(){         
      register();      
 }         
  function login(){        
      const name =document.getElementById('user');       
      const pass = document.getElementById('pass');            
      var xhr = new XMLHttpRequest();            
      console.log(name.value);            
      xhr.open('get', "http://localhost:8080/user?act=login&user="+name.value+"&pass="+pass.value, false);//直接用Alt+B打开时需加localhost            
      xhr.onreadystatechange = function(e) {      
                 if(xhr.readyState==4){              
                       if((this.status >= 200 && this.status < 300) || this.status == 304){            
                               var json= JSON.parse(this.responseText);//转换                   
                                console.log(json);                    
                                if(json.ok){                  
                                      alert("登录成功");                    
                                }else{            
                                     alert('登录失败:'+json.msg);            
                                }              
                        }else{               
                             alert("通信错误!");       
                         }           
                     };      
      }           
  xhr.send(null);        
 }      
  subBnt.onclick = function(){        
       login();     
     }  
       </script>
       </body>
       </html>

猜你喜欢

转载自blog.csdn.net/gaoshanyangzhi_1999/article/details/82988923
今日推荐