1.DAO层 操作数据库

1.utils

  1. //dbutil.js
  2. var mysql = require("mysql");
  3. function createConnection() {
  4. //连接数据库
  5. var connection = mysql.createConnection({
  6. host: "127.0.0.1",
  7. port: "3306",
  8. user: "root",
  9. password: "bugaosuni",
  10. database: "mydatabase"//连接的数据库
  11. });
  12. return connection;
  13. }
  14. module.exports.createConnection = createConnection;

2.封装查询函数

  1. //studentDao.js
  2. var dbutil = require("./dbutil");
  3. function queryAllStudent(success) {
  4. var querySql = "select * from student;";
  5. //创建连接
  6. var connection = dbutil.createConnection();
  7. //连接数据库
  8. connection.connect();
  9. //开始查询
  10. connection.query(querySql, function(error, result) {
  11. if (error == null) {
  12. console.log(result);
  13. //执行回调函数
  14. success(result);
  15. } else {
  16. console.log(error);
  17. }
  18. });
  19. //关闭连接
  20. connection.end();
  21. }
  22. function queryStudentByClassAndAge(classNum, age) {
  23. //防止sql注入
  24. var querySql = "select * from student where class = ? and age = ?;";
  25. //多个参数同时传入应该用数组
  26. var queryParams = [classNum, age];
  27. var connection = dbutil.createConnection();
  28. connection.connect();
  29. connection.query(querySql, queryParams, function(error, result) {
  30. if (error == null) {
  31. console.log(result);
  32. } else {
  33. console.log(error);
  34. }
  35. });
  36. connection.end();
  37. }
  38. function queryStudentByStuNum(stuNum, success) {
  39. var querySql = "select * from student where stu_num = ?;";
  40. var connection = dbutil.createConnection();
  41. connection.connect();
  42. connection.query(querySql, stuNum, function(error, result) {
  43. if (error == null) {
  44. console.log(result);
  45. success(result);
  46. } else {
  47. console.log(error);
  48. }
  49. });
  50. connection.end();
  51. }
  52. module.exports = {
  53. queryAllStudent: queryAllStudent,
  54. queryStudentByClassAndAge: queryStudentByClassAndAge,
  55. queryStudentByStuNum: queryStudentByStuNum
  56. };

2.service层 封装方法调用DAO层

  1. //输出API
  2. var studentDao = require("../dao/studentDao");
  3. function queryAllStudent(success) {
  4. studentDao.queryAllStudent(success);
  5. }
  6. function queryStudentByStuNum(stuNum, success) {
  7. studentDao.queryStudentByStuNum(stuNum, success);
  8. }
  9. module.exports = {
  10. queryAllStudent: queryAllStudent,
  11. queryStudentByStuNum: queryStudentByStuNum
  12. };

3.web层 controller处理接口调用service层的方法

  1. // loginController 调用API
  2. var studentService = require("../service/studentService");
  3. var url = require("url");
  4. var path = new Map();
  5. function getData(request, response) {
  6. studentService.queryAllStudent(function (result) {
  7. var resArr = [];
  8. for (var i = 0 ; i < result.length ; i ++) {
  9. resArr.push(result[i].name);
  10. }
  11. response.write(resArr.toString());
  12. response.end();
  13. });
  14. }
  15. path.set("/getData", getData);
  16. function login(request, response) {
  17. //post请求的data需在data事件中获取
  18. request.on("data", function(data){
  19. var stuNum = data.toString().split("&")[0].split("=")[1];
  20. var password = data.toString().split("&")[1].split("=")[1];
  21. studentService.queryStudentByStuNum(stuNum, function (result) {
  22. var res = "";
  23. if (result == null || result.length == 0) {
  24. res = "Fail";
  25. //location跳转,浏览器变更location
  26. response.writeHead(302, {"location": "/error.html"});
  27. response.end();
  28. } else {
  29. if (result[0].pwd == password) {
  30. res = "OK";
  31. response.writeHead(302, {"location": "/main.html", "Set-Cookie": "id=" + result[0].id});
  32. response.end();
  33. } else {
  34. res = "Fail";
  35. response.writeHead(302, {"location": "/error.html"});
  36. response.end();
  37. }
  38. }
  39. });
  40. });
  41. }
  42. path.set("/login", login);
  43. module.exports.path = path;

4.common

1.处理http请求模块

  1. var http = require("http");
  2. var url = require("url");
  3. var fs = require("fs");
  4. var globalConfig = require("./config");//config
  5. var loader = require("./loader");//web层controller
  6. var filterSet = require("./filterLoader");//拦截器
  7. var log = require("./log");//日志
  8. //生成server,监听对应host,port
  9. http.createServer(function (request, response) {
  10. //获取path和query
  11. var pathName = url.parse(request.url).pathname;
  12. var params = url.parse(request.url, true).query;
  13. log(pathName);//打印请求日志
  14. //拦截器
  15. for (var i = 0 ; i < filterSet.length ; i ++) {
  16. var flag = filterSet[i](request, response);
  17. if (!flag) {
  18. return;
  19. }
  20. }
  21. var isStatic = isStaticsRequest(pathName);
  22. if (isStatic) {//请求的静态文件
  23. try {
  24. var data = fs.readFileSync(globalConfig["page_path"] + pathName);
  25. response.writeHead(200);
  26. response.write(data);
  27. response.end();
  28. } catch (e) {
  29. response.writeHead(404);
  30. response.write("<html><body><h1>404 NotFound</h1></body></html>");
  31. response.end();
  32. }
  33. } else {//请求的动态的数据
  34. if (loader.get(pathName) != null) {
  35. //防止程序报错影响服务挂掉
  36. try {
  37. //根据不同path执行map中的函数
  38. loader.get(pathName)(request, response);
  39. } catch (e) {
  40. console.log(e);
  41. response.writeHead(500);
  42. response.write("<html><body><h1>500 BadServer</h1></body></html>");
  43. response.end();
  44. }
  45. } else {
  46. response.writeHead(404);
  47. response.write("<html><body><h1>404 NotFound</h1></body></html>");
  48. response.end();
  49. }
  50. }
  51. }).listen(globalConfig["port"]);
  52. //判断请求是否静态资源
  53. function isStaticsRequest(pathName) {
  54. for (var i = 0 ; i < globalConfig.static_file_type.length ; i ++) {
  55. var temp = globalConfig.static_file_type[i];
  56. if(pathName.indexOf(temp) == pathName.length - temp.length){
  57. return true;
  58. }
  59. }
  60. return false;
  61. }

2.loader.js 获取web层controller生成Map

  1. var fs = require("fs");
  2. var globalConfig = require("./config");
  3. var controllerSet = [];
  4. var pathMap = new Map();
  5. //读取web文件夹下的所有文件
  6. var files = fs.readdirSync(globalConfig["web_path"]); //[ 'TuLingAPI.js', 'fileUpload.js', 'loginController.js', 'test.js' ]
  7. for (var i = 0; i < files.length; i++) {
  8. var temp = require("./" + globalConfig["web_path"] + "/" + files[i]);
  9. if (temp.path) {
  10. //防止url重复
  11. for (var [key, value] of temp.path) {
  12. if (pathMap.get(key) == null) {
  13. pathMap.set(key, value);
  14. } else {
  15. throw new Error("url path异常,url:" + key);
  16. }
  17. controllerSet.push(temp);
  18. }
  19. }
  20. }
  21. //Map {
  22. // '/api/chat' => [Function: turingAPI],
  23. // '/testFileUpload' => [Function: testFileUpload],
  24. // '/getData' => [Function: getData],
  25. // '/login' => [Function: login]
  26. // }
  27. module.exports = pathMap;

3.log.js记录日志

  1. var fs = require("fs");
  2. var globalConfig = require("./config");
  3. var fileName = globalConfig.log_path + globalConfig.log_name;
  4. function log(data) {
  5. fs.appendFile(fileName, data + "\n",{flag:"a"} , function () {});
  6. }
  7. module.exports = log;

4.拦截器

  1. var url = require("url");
  2. var globalConfig = require("../config");
  3. function loginFilter(request, response) {
  4. var pathName = url.parse(request.url).pathname;
  5. if (pathName == "/login.html" || pathName == "/login" || isStaticsRequest(pathName)) {
  6. return true;
  7. }
  8. if (request.headers.cookie) {
  9. var cookies = request.headers.cookie.split(";");
  10. for (var i = 0 ; i < cookies.length ; i ++) {
  11. if (cookies[i].split("=")[0].trim() == "id") {
  12. return true;
  13. }
  14. }
  15. }
  16. response.writeHead(302, {"location": "/login.html"});
  17. response.end();
  18. return false;
  19. }
  20. function isStaticsRequest(pathName) {
  21. for (var i = 0 ; i < globalConfig.static_file_type.length ; i ++) {
  22. var temp = globalConfig.static_file_type[i];
  23. if (temp == ".html") {
  24. continue;
  25. }
  26. if(pathName.indexOf(temp) == pathName.length - temp.length){
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. module.exports = loginFilter;

5.filterloader.js 收集拦截器

  1. var fs = require("fs");
  2. var globalConfig = require("./config");
  3. var filterSet = [];
  4. var files = fs.readdirSync(globalConfig["filter_path"]);
  5. for (var i = 0 ; i < files.length ; i ++) {
  6. var temp = require("./" + globalConfig["filter_path"] + "/" + files[i]);
  7. filterSet.push(temp);
  8. }
  9. module.exports = filterSet;