weikee94 / blog-api

Node.js 从零开发web server博客项目
0 stars 0 forks source link

09 博客项目express 😎 #6

Open weikee94 opened 4 years ago

weikee94 commented 4 years ago

express 安装

express 脚手架

生成express project

weikee94 commented 4 years ago

express 路由

demo: access path would be /api/blog/detail

父路径

app.use("/api/blog", blogRouter);
app.use("/api/user", userRouter);

子路径

router.get("/detail", function (req, res, next) {
  res.json({
    error: 0,
    data: "okie",
  });
});
weikee94 commented 4 years ago

express middleware 中间件

只有执行next(),才会继续执行下去


// 模拟登录验证
function loginCheck(req, res, next) {
  console.log("模拟登录成功");
  setTimeout(() => {
    next();
  });
}

app.get("/api/get-cookie", loginCheck, (req, res, next) => {
  console.log("get /api/get-cookie");
  res.json({
    errno: 0,
    data: req.cookie,
  });
});
weikee94 commented 4 years ago

express redis session

const session = require("express-session");
const RedisStore = require("connect-redis")(session);

var app = express();

// redis handler
const redisClient = require("./db/redis");
const sessionStore = new RedisStore({
  client: redisClient,
});

app.use(
  session({
    secret: "aswqTha_1234@#$",
    cookie: {
      // path: "/", // 默认
      // httpOnly: true, // 默认
      maxAge: 24 * 60 * 60 * 1000,
    },
    //  引用session store
    store: sessionStore,
  })
);
weikee94 commented 4 years ago

express morgan

morgan middleware

// 日志
// dev || combined 是 log 不同显示格式
const ENV = process.env.NODE_ENV;
if (ENV !== "production") {
  // dev
  app.use(logger("dev"));
} else {
  // production
  // 写入log
  const logFileName = path.join(__dirname, "logs", "access.log");
  const writeStream = fs.createWriteStream(logFileName, {
    flags: "a",
  });
  app.use(
    logger("combined", {
      stream: writeStream,
    })
  );
}
weikee94 commented 4 years ago

中间件原理

参考lib/express/like-express to know more details