Native node. js Case Background and Background Interaction

  • 2021-07-22 08:52:07
  • OfStack

This case consists of four parts: (1) HTML; (2) ajax part; (3) JavaScript part; (4) node server part. In addition, because the server is involved, there is no "effect preview" here.

The execution process is as follows:

(1) Enter the website address in the address bar of the browser and send an HTML request to the node server; After receiving the request, the server returns an HTML file to the client;

(2) The client browser renders HTML and encounters < script > Tag, request to the server again, and the server responds to an JavaScript file to the client.

(3) The client browser renders the JavaScript file. In the rendering process, if the ajax request is encountered, the client will also request the server, and the server will still respond to the browser.

(4) Finally, the browser presents the rendered web page to the viewer.

1. HTML Part:


<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <title> Customer management system </title>
</head>
<body>
<div class="box">
 <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="link">NEW CUSTOMER</a>
 <h2>
  <span class="fir">ID</span>
  <span>NAME</span>
  <span class="fir">AGE</span>
  <span>PHONE</span>
  <span>ADDRESS</span>
  <span>CONTROL</span>
 </h2>
 <ul id="conList">
  <li>
   <span class="fir">1</span>
   <span> Qian Cheng </span>
   <span class="fir">25</span>
   <span>13044086186</span>
   <span>Bei Jing</span>
   <span class="control">
    <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" > Modify </a>
    <a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" > Delete </a>
   </span>
  </li>
 </ul>
</div>
<script charset="utf-8" type="text/javascript" src="js/ajax.js"></script>
<script charset="utf-8" type="text/javascript" src="js/index.js"></script>
</body>
</html>

2. ajax Part:


~function () {
 //->createXHR: Create AJAX Object , Compatible with all browsers 
 function createXHR() {
  var xhr = null,
   flag = false,
   ary = [
    function () {
     return new XMLHttpRequest;
    },
    function () {
     return new ActiveXObject("Microsoft.XMLHTTP");
    },
    function () {
     return new ActiveXObject("Msxml2.XMLHTTP");
    },
    function () {
     return new ActiveXObject("Msxml3.XMLHTTP");
    }
   ];
  for (var i = 0, len = ary.length; i < len; i++) {
   var curFn = ary[i];
   try {
    xhr = curFn();
    createXHR = curFn;
    flag = true;
    break;
   } catch (e) {
   }
  }
  if (!flag) {
   throw new Error("your browser is not support ajax,please change your browser,try again!");
  }
  return xhr;
 }
 //->ajax: Realization AJAX Requested public method ;
 function ajax(options) {
  var _default = {
   url: "",
   type: "get",
   dataType: "json",
   async: true,
   data: null,
   getHead: null,
   success: null
  };
  for (var key in options) {
   if (options.hasOwnProperty(key)) {
    _default[key] = options[key];
   }
  }
  if (_default.type === "get") {
   _default.url.indexOf("?") >= 0 ? _default.url += "&" : _default.url += "?";
   _default.url += "_=" + Math.random();
  }
  //->SEND AJAX
  var xhr = createXHR();
  xhr.open(_default.type, _default.url, _default.async);
  xhr.onreadystatechange = function () {
   if (/^2\d{2}$/.test(xhr.status)) {
    if (xhr.readyState === 2) {
     if (typeof _default.getHead === "function") {
      _default.getHead.call(xhr);
     }
    }
    if (xhr.readyState === 4) {
     var val = xhr.responseText;
     if (_default.dataType === "json") {
      val = "JSON" in window ? JSON.parse(val) : eval("(" + val + ")");
     }
     _default.success && _default.success.call(xhr, val);
    }
   }
  };
  xhr.send(_default.data);
 }
 window.ajax = ajax;
}();

3. JavaScript Part:


var customer = (function () {
 var conList = document.getElementById('conList');
 function bindEvent() {
  conList.onclick = function (ev) {
   ev = ev || window.event;
   var tar = ev.target || ev.srcElement,
    tarTag = tar.tagName.toUpperCase(),
    tarInn = tar.innerHTML;
   if (tarTag === 'A' && tarInn === ' Delete ') {
    //->ALERT , CONFIRM , PROMPT
    var cusId = tar.getAttribute('data-id'),
     flag = window.confirm(' Are you sure you want to delete the  [ ' + cusId + ' ]  Is it a customer of ?');
    if (flag) {//-> Click the OK button : Call the corresponding API Interface implementation can be deleted 
     ajax({
      url: '/removeInfo?id=' + cusId,
      cache: false,
      success: function (result) {
       if (result && result.code == 0) {
        //-> After successful deletion, HTML Structure to remove the corresponding LI Label 
        conList.removeChild(tar.parentNode.parentNode);
       }
      }
     });
    }
   }
  }
 }
 function bindHTML(data) {
  var str = '';
  for (var i = 0; i < data.length; i++) {
   var cur = data[i];
   str += '<li>';
   str += '<span class="fir">' + cur.id + '</span>';
   str += '<span>' + cur.name + '</span>';
   str += '<span class="fir">' + cur.age + '</span>';
   str += '<span>' + cur.phone + '</span>';
   str += '<span>' + cur.address + '</span>';
   str += '<span class="control">';
   str += '<a href="add.html?id=' + cur.id + '" rel="external nofollow" > Modify </a>';
   str += '<a href="javascript:;" rel="external nofollow" data-id="' + cur.id + '"> Delete </a>';
   str += '</span>';
   str += '</li>';
  }
  conList.innerHTML = str;
 }
 return {
  init: function () {
   ajax({
    url: '/getAllList',
    type: 'GET',
    dataType: 'JSON',
    cache: false,
    success: function (result) {
     if (result && result.code == 0) {
      bindHTML(result.data);
      bindEvent();
     }
    }
   });
  }
 }
})();
customer.init();

4. node server part:


var http = require("http");
var url = require("url");
var fs = require("fs");
var server1 = http.createServer(function (request, response) {
 var urlObj = url.parse(request.url, true);
 var pathname = urlObj.pathname;
 var query = urlObj.query;
 var reg = /\.(HTML|CSS|JS|ICO)/i;
 if (reg.test(pathname)) {
  var suffix = reg.exec(pathname)[1].toUpperCase();
  var suffixMIME = suffix === 'HTML' ? 'text/html' : (suffix === 'CSS' ? 'text/css' : 'text/javascript');
  try {
   var conFile = fs.readFileSync('.' + pathname, 'utf-8');
   response.writeHead(200, {'content-type': suffixMIME + ';charset=utf-8;'});
   response.end(conFile);
   // With conFile End the response to the client, that is, return to the client ./index.html For the client to render into a page. 
  } catch (e) {
   response.writeHead(404, {'content-type': 'text/plain;charset=utf-8;'});
   response.end('request file is not found!');
  }
  return;
 }
 //-> Data API Request processing : Client's JS In the code, we pass AJAX Requests sent to the server , The server receives the request and 
 //  Get the data passed by the client , Prepare the required data content , Then return to the client , Client in AJAX Adj. READY
 // STATE Equal to 4 Gets the returned content when the ( It's all in accordance with API To process the specification document of )
 var customData = fs.readFileSync('./json/custom.json', 'utf-8');
 customData.length === 0 ? customData = '[]' : null;
 customData = JSON.parse(customData);
 var result = {
  code: 1,
  msg: ' Failure ',
  data: null
 };
 var customId = null;
 //1) Get all customer information 
 if (pathname === '/getAllList') {
  if (customData.length > 0) {
   result = {
    code: 0,
    msg: ' Success ',
    data: customData
   };
  }
  response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
  response.end(JSON.stringify(result));
  return;
 }
 //2) Get the specified customer information 
 if (pathname === '/getInfo') {
  customId = query['id'];
  customData.forEach(function (item, index) {
   if (item['id'] == customId) {
    result = {
     code: 0,
     msg: ' Success ',
     data: item
    };
   }
  });
  response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
  response.end(JSON.stringify(result));
  return;
 }
 //3) Add customer information 
 if (pathname === '/addInfo') {
  var str = '';
  request.on('data', function (chunk) {
   str += chunk;
  });
  request.on('end', function () {
   var data = JSON.parse(str);
   data['id'] = customData.length === 0 ? 1 : parseFloat(customData[customData.length - 1]['id']) + 1;
   customData.push(data);
   fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
   result = {
    code: 0,
    msg: ' Success '
   };
   response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
   response.end(JSON.stringify(result));
  });
  return;
 }
 //4) Modify customer information 
 if (pathname === '/updateInfo') {
  str = '';
  request.on('data', function (chunk) {
   str += chunk;
  });
  request.on('end', function () {
   var data = JSON.parse(str),
    flag = false;
   for (var i = 0; i < customData.length; i++) {
    if (data['id'] == customData[i]['id']) {
     customData[i] = data;
     flag = true;
     break;
    }
   }
   if (flag) {
    fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
    result = {
     code: 0,
     msg: ' Success '
    };
   }
   response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
   response.end(JSON.stringify(result));
  });
  return;
 }
 //5) Delete customer information 
 if (pathname === '/removeInfo') {
  customId = query['id'];
  var flag = false;
  customData.forEach(function (item, index) {
   if (item['id'] == customId) {
    customData.splice(index, 1);
    flag = true;
   }
  });
  if (flag) {
   fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
   result = {
    code: 0,
    msg: ' Success '
   };
  }
  response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
  response.end(JSON.stringify(result));
  return;
 }
 response.writeHead(404, {'content-type': 'text/plain;charset=utf-8;'});
 response.end('request url is not found!');
});
server1.listen(80, function () {
 console.log("server is success,listening on 80 port!");
});

Related articles: