r3f.cn
GitHub Repo stars

Express

Express 快速参考备忘单,一个灵活且简化的 Node.js Web 框架。

#快速入门

#Hello World

  • "创建项目,添加 package.json 配置

    $ mkdir myapp # 创建目录
    $ cd myapp    # 进入目录
    $ npm init -y # 初始化配置
    
  • 安装依赖

    $ npm install express
    
  • 入口文件 index.js 添加代码:

    const express = require("express");
    const app = express();
    const port = 3000;
    app.get("/", (req, res) => {
      res.send("Hello World!");
    });
    app.listen(port, () => {
      console.log(`监听端口 ${port}`);
    });
    
  • 使用以下命令运行应用程序

    $ node index.js
    

#express -h

用法: express [选项] [目录]
选项:
  -h, --help 输出用法信息
      --version 输出版本号
  -e, --ejs 添加 ejs 引擎支持
      --hbs 添加 hbs 引擎支持
      --pug 添加 pug 引擎支持
  -H, --hogan 添加 hogan.js 引擎支持
      --no-view 不生成视图引擎
  -v, --view <引擎> 添加视图 <引擎> 支持 (ejs|hbs|hjs|jade|pug|twig|vash) (默认为 jade)
  -c, --css <引擎> 添加样式表 <引擎> 支持 (less|stylus|compass|sass) (默认为 css)
      --git 添加 .gitignore
  -f, --force 强制操作非空目录

创建一个 myapp 项目

$ express --view=pug myapp
# 运行应用程序
$ DEBUG=myapp:*npm start

#express()

:- :-
express.json() #
express.raw() #
express.Router() #
express.static() #
express.text() #
express.urlencoded() #

#路由 (Router)

:- :-
router.all() #
router.METHOD() #
router.param() #
router.route() #
router.use() #

#应用程序 (Application)

var express = require("express");
var app = express();

console.dir(app.locals.title);
//=> 'My App'
console.dir(app.locals.email);
//=> '[email protected]'

#属性 (Attribute)

:- :-
app.locals 应用程序中的局部变量 #
app.mountpath 用于挂载子应用程序的路径模式 #

#事件 (Events)

:- :-
mount 子应用程序挂载到父应用程序时,在子应用程序上触发该事件 #

#方法 (Method)

:- :-
app.all() #
app.delete() #
app.disable() #
app.disabled() #
app.enable() #
app.enabled() #
app.engine() #
app.get(name) #
app.get(path, callback) #
app.listen() #
app.METHOD() #
app.param() #
app.path() #
app.post() #
app.put() #
app.render() #
app.route() #
app.set() #
app.use() #

#请求 (Request)

#属性 (Attribute)

:- :-
req.app #
req.baseUrl #
req.body #
req.cookies #
req.fresh #
req.hostname #
req.ip #
req.ips #
req.method #
req.originalUrl #
req.params #
req.path #
req.protocol #
req.query #
req.route #
req.secure #
req.signedCookies #
req.stale #
req.subdomains #
req.xhr #

#方法 (Method)

:- :-
req.accepts() #
req.acceptsCharsets() #
req.acceptsEncodings() #
req.acceptsLanguages() #
req.get() 获取 HTTP 请求头字段 #
req.is() #
req.param() #
req.range() #

#响应 (Response)

app.get("/", function (req, res) {
  console.dir(res.headersSent); //false
  res.send("OK");
  console.dir(res.headersSent); //true
});

#属性 (Attribute)

:- :-
res.app #
res.headersSent #
res.locals #

#方法 (Method)

:- :-
res.append() #
res.attachment() #
res.cookie() #
res.clearCookie() #
res.download() 提示文件下载 #
res.end() 结束响应过程 #
res.format() #
res.get() #
res.json() 发送 JSON 响应 #
res.jsonp() 发送支持 JSONP 的响应 #
res.links() #
res.location() #
res.redirect() 重定向请求 #
res.render() 渲染视图模板 #
res.send() 发送各种类型的响应 #
res.sendFile() 以八位字节流形式发送文件 #
res.sendStatus() #
res.set() #
res.status() #
res.type() #
res.vary() #

#示例 (Example)

#路由 (Router)

对传递给此路由器的任何请求调用

router.use(function (req, res, next) {
  //.. 一些逻辑在这里 .. 像任何其他中间件一样
  next();
});

将处理任何以 /events 结尾的请求

//取决于路由器 "use()" 的位置
router.get("/events", (req, res, next) => {
  //..
});

#响应 (Response)

res 对象表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应

app.get("/user/:id", (req, res) => {
  res.send("user" + req.params.id);
});

#请求 (Request)

req 对象表示一个 HTTP 请求,并具有请求查询字符串、参数、正文、HTTP 头等属性。

app.get("/user/:id", (req, res) => {
  res.send("user" + req.params.id);
});

#res.end()

res.end();
res.status(404).end();

结束响应过程。此方法实际上来自 Node 核心,特别是 http.ServerResponseresponse.end() 方法。

#res.json([body])

res.json(null);
res.json({ user: "tobi" });
res.status(500).json({ error: "message" });

#app.all

app.all("/secret", function (req, res, next) {
  console.log("访问秘密区域...");
  next(); // 将控制权传递给下一个处理程序
});

#app.delete

app.delete("/", function (req, res) {
  res.send("向主页发出 DELETE 请求");
});

#app.disable(name)

app.disable("trust proxy");
app.get("trust proxy");
// => false

#app.disabled(name)

app.disabled("trust proxy");
// => true

app.enable("trust proxy");
app.disabled("trust proxy");
// => false

#app.engine(ext, callback)

var engines = require("consolidate");

app.engine("haml", engines.haml);
app.engine("html", engines.hogan);

#app.listen([port[, host[, backlog]]][, callback])

var express = require("express");

var app = express();
app.listen(3000);

#路由 (Routing)

const express = require("express");
const app = express();

//向主页发出 GET 请求时响应 "hello world"
app.get("/", (req, res) => {
  res.send("hello world");
});
// GET 方法路由
app.get("/", (req, res) => {
  res.send("向主页发出 GET 请求");
});

// POST 方法路由
app.post("/", (req, res) => {
  res.send("向主页发出 POST 请求");
});

#中间件 (Middleware)

function logOriginalUrl(req, res, next) {
  console.log("请求URL:", req.originalUrl);
  next();
}

function logMethod(req, res, next) {
  console.log("请求类型:", req.method);
  next();
}

const log = [logOriginalUrl, logMethod];

app.get("/user/:id", log, (req, res, next) => {
  res.send("用户信息");
});

#使用模板 (Using templates)

app.set("view engine", "pug");

views 目录中创建一个名为 index.pugPug 模板文件,内容如下:

html
  head
    title= title
  body
    h1=message

创建一个路由来渲染 index.pug 文件。如果未设置视图引擎属性,则必须指定视图文件的扩展名。

app.get("/", (req, res) => {
  res.render("index", {
    title: "嘿",
    message: "你好!",
  });
});