nodejs——express框架的简单实现

const url = require("url");
const fs = require("fs");
const path = require("path");
let G = {
  _get: {},
  _post: {},
  static: "static",
};

const changeRes = (res) => {
  res.send = (data) => {
    res.writeHead(200, { "Content-type": "text/plain;charset=utf-8" });
    res.end(JSON.stringify(data));
  };
};
const initStatic = (res, pathname) => {
  try {
    const extname = path.extname(pathname);
    let type;
    try {
      const jsonData = JSON.parse(fs.readFileSync("./mime.json"));
      type = jsonData[extname];
    } catch (err) {
      //   console.log(err);
    }
    let data = fs.readFileSync("./" + G.static + pathname);
    res.writeHead(200, { "Content-type": `${type};charset=utf-8` });
    res.end(data);
  } catch (err) {}
};

const app = (req, res) => {
  const pathname =
    url.parse(req.url).pathname == "/"
      ? "/index.html"
      : url.parse(req.url).pathname;
  changeRes(res);
  initStatic(res, pathname);

  if (req.method === "GET") {
    if (G._get[pathname]) {
      G._get[pathname](req, res);
    }
  } else {
    if (G._post[pathname]) {
      let data = "";
      req.on("data", (chunk) => {
        data += chunk;
      });
      req.on("end", () => {
        req.body = data;
        G._post[pathname](req, res);
      });
    }
  }
};

app.get = (pathname, cb) => {
  G._get[pathname] = cb;
};
app.post = (pathname, cb) => {
  G._post[pathname] = cb;
};
app.static = (path) => {
  G.static = path;
};
module.exports = app;

使用

const http = require("http");
const app = require("./express");
const qs = require("querystring");
const { MongoClient } = require("mongodb");
http.createServer(app).listen(8080);

app.get("/test", (req, res) => {
  MongoClient.connect("mongodb://127.0.0.1:27017/", (err, client) => {
    if (err) {
      res.send({ code: 200, msg: err });
      return;
    }
    const db = client.db("itying");
    const order_collection = db.collection("order");
    order_collection
      .aggregate([
        {
          $lookup: {
            from: "order",
            localField: "order_id",
            foreignField: "order_id",
            as: "items",
          },
        },
      ])
      .toArray((err, data) => {
        if (err) {
          res.send({ code: 200, msg: err });
          client.close();
          return;
        }
        res.send({ code: 200, msg: "", data });
        client.close();
        return;
      });
  });
});
app.post("/register", (req, res) => {
  res.send(qs.parse(req.body));
});
app.static("public");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱学习的前端小黄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值