2019-06-18 简易node原生http服务器

2019-06-18  本文已影响0人  DreamNeverDie

server.js

const http=require('http');
const fs=require('fs');
const querystring=require('querystring');
const urlLib=require('url');

var users={};   //{"blue": "123456", "zhangsan": "123456", "lisi": "321321"}

var server=http.createServer(function (req, res){
  //解析数据
  var str='';
  req.on('data', function (data){
    str+=data;
  });
  req.on('end', function (){
    var obj=urlLib.parse(req.url, true);

    const url=obj.pathname;
    const GET=obj.query;
    const POST=querystring.parse(str);

    //区分——接口、文件
    if(url=='/user'){   //接口
      switch(POST.act){
        case 'reg':
          //1.检查用户名是否已经有了
          if(users[POST.user]){
            res.write('{"ok": false, "msg": "此用户已存在"}');
          }else{
            //2.插入users
            users[POST.user]=POST.pass;
            res.write('{"ok": true, "msg": "注册成功"}');
          }
          break;
        case 'login':
          //1.检查用户是否存在
          if(users[POST.user]==null){
            res.write('{"ok": false, "msg": "此用户不存在"}');
          //2.检查用户密码
          }else if(users[POST.user]!=POST.pass){
            res.write('{"ok": false, "msg": "用户名或密码有误"}');
          }else{
            res.write('{"ok": true, "msg": "登录成功"}');
          }
          break;
        default:
          res.write('{"ok": false, "msg": "未知的act"}');
      }
      res.end();
    }else{              //文件
      //读取文件
      var file_name='./www'+url;
      fs.readFile(file_name, function (err, data){
        if(err){
          res.write('404');
        }else{
          res.write(data);
        }
        res.end();
      });
    }
  });
});

server.listen(8080);

ajax.js

/**
 *  Author:strive
 *  Date: 2016/1/13
 */
function json2url(json){
    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    }
    return arr.join('&');
}

function ajax(json){
    json=json || {};
    if(!json.url)return;
    json.data=json.data || {};
    json.type=json.type || 'get';

    if(window.XMLHttpRequest){
        var oAjax=new XMLHttpRequest();
    }else{
        var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
    }

    switch(json.type){
        case 'get':
            oAjax.open('GET',json.url+'?'+json2url(json.data),true);
            oAjax.send();
            break;
        case 'post':
            oAjax.open('POST',json.url,true);
            oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            oAjax.send(json2url(json.data));
            break;
    }


    oAjax.onreadystatechange=function(){
        if(oAjax.readyState==4){
            if(oAjax.status>=200 && oAjax.status<300 || oAjax.status==304){
                json.success && json.success(oAjax.responseText);
            }else{
                json.error && json.error(oAjax.status);
            }
        }
    };
}

客户端使用

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="ajax.js" charset="utf-8"></script>
    <script type="text/javascript">
      window.onload=function (){
        var oTxtUser=document.getElementById('user');
        var oTxtPass=document.getElementById('pass');
        var oBtnReg=document.getElementById('reg_btn');
        var oBtnLogin=document.getElementById('login_btn');

        oBtnLogin.onclick=function (){
          ajax({
            url: '/user',
            data: {act: 'login', user: oTxtUser.value, pass: oTxtPass.value},
            type: 'post',
            success: function (str){
              var json=eval('('+str+')');

              if(json.ok){
                alert('登录成功');
              }else{
                alert('登录失败:'+json.msg);
              }
            },
            error: function (){
              alert('通信错误');
            }
          });
        };

        oBtnReg.onclick=function (){
          ajax({
            url: '/user',
            data: {act: 'reg', user: oTxtUser.value, pass: oTxtPass.value},
            type: 'post',
            success: function (str){
              var json=eval('('+str+')');

              if(json.ok){
                alert('注册成功');
              }else{
                alert('注册失败:'+json.msg);
              }
            },
            error: function (){
              alert('通信错误');
            }
          });
        };
      };
    </script>
  </head>
  <body>
    用户:<input type="text" id="user"><br>
    密码:<input type="password" id="pass"><br>
    <input type="button" value="注册" id="reg_btn">
    <input type="button" value="登录" id="login_btn">
  </body>
</html>

上一篇 下一篇

猜你喜欢

热点阅读