Open weikee94 opened 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",
});
});
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,
});
});
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,
})
);
express morgan
// 日志
// 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,
})
);
}
中间件原理
参考lib/express/like-express to know more details
express 安装
express 脚手架
npm install express-generator -g
生成express project
express projectName