marp | paginate | style |
---|---|---|
true |
true |
h1 {
color: #0bb8e8;
}
|
Fast, unopinionated, minimalist web framework for node.
- 快速
- 无偏见
- 最小化的
- Web 框架
作者:TJ Holowaychuk
- Application
- Router
- Request
- Response
作用:
将 Web 开发的常规操作简化
一个机制:中间件
即 Exepress 应用本身。
主要功能包括:
- 路由
- 中间件
- 模板引擎注册与渲染
路由器,一个小型的 Application
主要处理:
- 路由
- 中间件
HTTP 请求对象 包含了 query 字串,参数,body,头等相关的 HTTP 请求信息。
通常使用 req 表示
表示 HTTP 的响应对象,当有 HTTP 请求发起时就会创建。
通常使用 res 表示
var express = require("express");
var app = express();
app.get("/", function(req, res) {
res.send("Hello World\n");
});
app.listen(3000);
安装
npm install express --save
express 最强大的部分是中间件 在中间件里,可以插入各种各样的服务
中间件实际就是一个异步函数。
注意事项:
- 中间件是有顺序的
- 中间件是线性的
- 中间件优先于最终请求处理被执行
app.use(function(req, res, next) {
// 必须调用next函数
next();
});
app.use(function(req, res, next) {
req.data = "mid";
next();
});
多种形式
- 直接路径
app.get("/hello", function(req, res) {
res.send("Hello World!");
});
- 带有参数
app.get("/hello", function(req, res) {
res.send("Hello World!");
});
app.get("/users/:id", function(req, res) {
res.send("Hello World!");
});
app.post("/users/:id", function(req, res) {
res.send("Hello World!");
});
app.post("/users/:id/:attribute", function(req, res) {
res.send("Hello World!");
});
var express = require("express");
var app = express();
app.use(express.static("public"));
app.use("/static", express.static("public"));
app.listen(3000);
- pug
- ejs
- nunjucks
推荐 nunjucks,功能最强大
npm i nunjucks
var express = require("express");
var nunjucks = require("nunjucks");
var app = express();
nunjucks.configure("views", {
autoescape: true,
express: app
});
app.get("/", function(req, res) {
res.render("index.html", { username: "hello" });
});
app.listen(8080);
res.render = function(filename, options) {
// 读取模板文件
fs.readFile("templates/main.html", function(err, data) {
if (err) {
console.log(err);
return;
}
var content = String(data);
var test = /{{(.*)}}/.test(content);
if (test) {
var key = RegExp.$1;
if (key && options[key]) {
content = content.replace("{{" + key + "}}", options[key]);
}
}
res.write(content);
res.end();
});
};
- 设置 cookies
var express = require("express");
var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
app.get("/", function(req, res) {
res.cookie("name", "express").send("cookie set"); //Sets name = express
});
app.listen(3000);
- 读取 cookie
console.log("Cookies: ", req.cookies);
- 添加过期时间
res.cookie(name, "value", { expire: 360000 + Date.now() });
res.cookie(name, "value", { maxAge: 360000 });
- 删除
res.clearCookie("foo");
var express = require("express");
var session = require("express-session");
var app = express();
app.use(session({ secret: "sosos" }));
app.get("/", function(req, res) {
if (req.session.page_views) {
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
app.listen(3000);
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
// for parsing application/www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/", function(req, res) {
console.log(req.body);
res.send("recieved your request!");
});
app.listen(3000);
var express = require("express");
var multer = require("multer");
var upload = multer();
var app = express();
// for parsing multipart/form-data
app.use(upload.any());
app.post("/", function(req, res) {
console.log(req.file);
console.log(req.files);
res.send("recieved your request!");
});
app.listen(3000);
示例:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();
var session = require("express-session");
var cookieParser = require("cookie-parser");
app.set("view engine", "pug");
app.set("views", "./views");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());
app.use(cookieParser());
app.use(session({ secret: "Your secret key" }));
var Users = [];
app.get("/signup", function(req, res) {
res.render("signup");
});
app.post("/signup", function(req, res) {
if (!req.body.id || !req.body.password) {
res.status("400");
res.send("Invalid details!");
} else {
Users.filter(function(user) {
if (user.id === req.body.id) {
res.render("signup", {
message: "User Already Exists! Login or choose another user id"
});
}
});
var newUser = { id: req.body.id, password: req.body.password };
Users.push(newUser);
req.session.user = newUser;
res.redirect("/protected_page");
}
});
app.listen(3000);
用户登录实际就是
- 将用户信息进行匹配
- 发送 token 建立 session
- 基于 session 授权用户操作
通常会有这样的操作
req.session.user = user;
即获取 body, query, params
app.post("/users/:id", function(req, res) {
req.body;
req.params;
req.query;
res.send("Hello World!");
});
即获取 body, query, params
app.post("/users/:id", function(req, res) {
req.body;
req.params;
req.query;
res.send("Hello World!");
});
- 安装
npm install -g express-generator@4
- 创建应用
express /tmp/foo && cd /tmp/foo
- 安装依赖
npm install
- 启动服务器
npm start