美文网首页
模块封装基础

模块封装基础

作者: Wrestle_Mania | 来源:发表于2019-11-19 15:59 被阅读0次
    • routes.js
    const http = require("http");
    const url = require("url");
    const model = require("./model/model.js");
    
    http
      .createServer((req, res) => {
        res.writeHead(200, { "Content-Type": "text/html;charset=utf8" });
        let pathname = url.parse(req.url).pathname.replace("/", "");
        if (pathname !== "favicon.ico") {
          try {
            model[pathname](req, res);
          } catch (e) {
            model["error404"](req, res);
          } finally {
          }
        }
      })
      .listen(8080);
    
    • model/model.js
    const ejs = require("ejs");
    const url = require("url");
    const fs = require("fs");
    
    const app = {
      login(req, res) {
        ejs.renderFile("views/form.ejs", {}, (err, str) => {
          if (err) throw err;
          res.end(str);
        });
      },
      register(req, res) {
        res.end("register");
      },
      doLogin(req, res) {
        let { query } = url.parse(req.url, true);
        if (req.method === "GET") {
          res.end("doLogin");
        } else if (req.method === "POST") {
          let str = "";
          req.on("data", chunk => {
            str += chunk;
          });
          req.on("end", (err, data) => {
            if (err) throw err;
            fs.appendFile("fuck.txt", `${str}\n`, err => {
              if (err) throw err;
              console.log("文件写入成功");
            });
            res.end("<script>alert('登录成功');history.back();</script>");
          });
        }
      },
      error404(req, res) {
        res.end("404");
      }
    };
    
    module.exports = app;
    

    稍微变的简洁了,但是还不是我想要的

    相关文章

      网友评论

          本文标题:模块封装基础

          本文链接:https://www.haomeiwen.com/subject/wztgictx.html