最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 【学习笔记】Express 的 API 有哪些?这里全了

    正文概述 掘金(swanf)   2020-12-30   470

    What is Express

    Express 是一个类似 Flask 一样的用于构建后端 Node 应用(页面放在了 views 中,路由放在了 router 中)的可插拔性极强(可理解为能够用中间件方便地组装功能)的框架。

    Why

    它能够快速构建应用或 API,并且是 unopinionated(无特定开发风格倾向)的,灵活且配置简单。

    How

    5.x API

    express()

    想要创建一个 Express 应用,express() 方法是 express 模块给出的最高层 top-level 的函数。直接执行它,这将为我们带来一个 Express 应用对象。

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

    express.json([options])

    返回一个 express 自带的中间件,express 应用能对传入应用的请求的 req.body 进行 JSON 的解析(基于 body-parser)。

    注意:req.body 中的内容需要保持警惕,防范 XSS。因此需要对所有用户输入进行验证和转义才能使用。

    options:inflate、limit、reviver、strict、type、verify

    所有的中间件需要“使用”(use)它才能生效,即 app.use(express.json())

    express.urlencoded([options])

    返回一个 express 自带的中间件,express 应用能对传入应用的请求的 req.body 的 urlencoded 内容进行解析(基于 body-parser,只对 Content-Type 和 options 中的 type 匹配的请求有效)。

    options:extended、inflate、limit、parameterLimit、type、verify

    express.static(root, [options])

    返回一个 express 自带的中间件,它能够提供对静态文件的访问(基于 serve-static)。

    root 是静态资源所在的路径,每个静态资源都需要用一次 express.static()

    Express 应用找不到静态资源不会返回 404,而是会调用 next() 方法去移向下一个中间件,从而能够栈式调用(如使用一个 error handler 中间件)和进行回退。

    注意:使用 nginx 之类的反向代理能够缓存静态资源,优化性能。

    options 是一个对象,定义了访问静态资源时的一些行为,不展开了。

    const options = {
      dotfiles: "ignore",
      etag: false,
      extensions: ["htm", "html"],
      index: false,
      maxAge: "1d",
      redirect: false,
      setHeaders: function (res, path, stat) {
        res.set("x-timestamp", Date.now());
      },
    };
    
    app.use(express.static("public", options));
    

    express.Router([options])

    注意:这里的 R 是大写的,因为它返回的不是一个中间件,而是一个 Router 对象。

    options 是一个对象,定义了访问路由时的一些行为 {caseSensitive: Boolean, mergeParams: Boolean, strict: Boolean},三种行为的的默认都是 false

    const router = express.Router([options]);
    

    Router 对象可以看作是一个“mini 应用”,它是一个和 routes 及 Express 应用是完全独立的实例,能够使用中间件和 routing function(getpostdelete 等)。

    Express 对象使用 Router 对象:

    app.use("/calendar", router);
    

    常见方法:router.all()router.METHOD()router.param()router.route()router.use()

    Application

    通常 app 对象用来指代 Express 应用,它是由 top-level 的 express() 函数执行后返回的。

    它能够对 http 请求进行路由导航(app.METHOD/app.param)、配置中间件(app.route)、渲染 html 页面(app.render)、注册模板引擎(app.engine

    Express 应用对象能够以 req.appres.app 的方式在 res 和 req 中被获取到。

    属性)app.locals

    定义了应用中能够使用的本地变量,类似 react 的 this.state,一旦设置变量能够在整个应用生命过程中使用。而 res.locals 则只能够在请求的生命过程中使用。

    在中间件中使用 app.locals :通过 req 调用, req.app.locals

    app.mountpath

    包含一个或多个已将子 app 挂载了的路径,子 app (sub-app)是一个用于处理对路由请求的 Express 实例,其实和 Router 实例是一回事。

    const express = require("express");
    
    const app = express(); // the main app
    const admin = express(); // the sub app
    
    admin.get("/", function (req, res) {
      console.log(admin.mountpath); // /admin // 因为 admin 之后被挂载在 "/admin" 上了
      res.send("Admin Homepage");
    });
    
    app.use("/admin", admin); // mount the sub app // 和挂载 router 的时候一样
    

    app.router

    应用内置路由,比起上面 admin 这种 sub-app,它不需要使用 app.use 挂载就可以直接导航

    var express = require("express");
    var app = express();
    var router = app.router;
    
    router.get("/", function (req, res) {
      res.send("hello world");
    });
    
    app.listen(3000);
    

    事件)app.on('mount', callback(parent))

    app 事件:'mount'

    当子 app 挂载到父 app 上的时候触发,父 app 被当作参数传到回调函数里去。

    const admin = express();
    
    admin.on("mount", function (parent) {
      console.log("Admin Mounted");
      console.log(parent); // refers to the parent app
    });
    
    admin.get("/", function (req, res) {
      res.send("Admin Homepage");
    });
    
    app.use("/admin", admin);
    

    方法)app.all(path, callback[, callback ...])

    能够匹配所有 http 动作的方法。path 是触发回调函数的路径, callback 是一个/一系列回调函数(也叫中间件函数)

    app.all("/secret", function (req, res, next) {
      console.log("Accessing the secret section ...");
      next(); // pass control to the next handler
    });
    

    app.METHOD(path, callback [, callback ...])

    包含各种常见 http 动作的请求处理: app.delete(path, callback [, callback ...]) app.get(path, callback [, callback ...]) app.post(path, callback [, callback ...]) app.put(path, callback [, callback ...])

    全部的 http 动作列表如下:

    checkout copy delete get head lock merge mkactivity mkcol move m-search notify options patch post purge put report search subscribe trace unlock unsubscribe

    app.get(name)

    注意这个是重载函数,和 http 动作那个 get 不同,这个是从 app 的 settings 里面取出一个键为 name 所对应的值.

    app.disable(name)

    设置 app settings 的对应键的值为 false,等价于app.set(name, false)

    app.disabled(name)

    返回一个 boolean,即对应 app settings 的对应键的值是否为 false。

    app.enable(name)

    设置 app settings 的对应键的值为 true,app.set(name, true)

    app.enabled(name)

    返回一个 boolean,即对应 app settings 的对应键的值是否为 true。

    app.engine(ext, callback)

    为拓展名为 ext 的文件注册一个给定的模板引擎 callback。

    app.listen(path, [callback])

    开启一个 UNIX 的套接字,开始监听给定的连接。等价于 node 的 http.Server.listen() 方法。

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

    又是一个重载的函数,而且这个最常见:绑定和监听指定主机和端口的连接。

    app.listen() 会返回一个 http.Server 对象他内部其实是这样的:

    app.listen = function () {
      var server = http.createServer(this);
      return server.listen.apply(server, arguments);
    };
    

    app.param(name, callback)

    添加一个路由参数的触发回调函数,每当 路由 URL 中出现了 name(在参数中或者在参数数组中),都会触发这个 callback 函数执行。

    app.param(["id", "page"], function (req, res, next, value) {
      console.log("CALLED ONLY ONCE with", value);
      next();
    });
    
    app.get("/user/:id/:page", function (req, res, next) {
      console.log("although this matches");
      next();
    });
    
    app.get("/user/:id/:page", function (req, res) {
      console.log("and this matches too");
      res.end();
    });
    
    /**
     * On  GET /user/42/3
     *
     * output:
     *
     * CALLED ONLY ONCE with 42
     * CALLED ONLY ONCE with 3
     * although this matches
     * and this matches too
     **/
    

    app.path()

    返回一个当前 app 的规范 canonical 路径(一个字符串)。通常使用建议 req.baseUrl

    const app = express();
    const blog = express();
    const blogAdmin = express();
    
    app.use("/blog", blog);
    blog.use("/admin", blogAdmin);
    
    console.log(app.path()); // ''
    console.log(blog.path()); // '/blog'
    console.log(blogAdmin.path()); // '/blog/admin'
    

    app.render(view, [locals], callback)

    通过 callback 返回一个 view 的渲染好的 HTML。它接受一个额外的参数 locals,包含这个 view 里面要使用到的本地变量。类似于 res.render() 但是它不能自个通过后台 app 发送渲染好的 view 到客户端。

    app.render("email", { name: "Tobi" }, function (err, html) {
      // ...
    });
    

    app.route(path)

    返回一个单路径路由,能够使用链式调用,用来处理该路径上面的所有 http 动作,防止重复写路由。

    const app = express();
    
    app
      .route("/events")
      .all(function (req, res, next) {
        // runs for all HTTP verbs first
        // think of it as route specific middleware!
      })
      .get(function (req, res, next) {
        res.json({});
      })
      .post(function (req, res, next) {
        // maybe add a new event...
      });
    

    app.use([path,] callback [, callback...])

    用于挂载中间件的函数(们)。还能指定路径,让中间件在指定路径才发挥作用。

    注意:这个指定的路径会匹配所有 path + '/' + somethingElse 的路径,如 app.use('/apple', ...) 能匹配到 /apple/apple/images/apple/images/news

    根据这个规则,没指定的 path 取默认值/,因此能匹配到所有的路径,对所有请求这个中间件函数都会执行。

    app.use(function (req, res, next) {
      console.log("Time: %d", Date.now());
      next();
    });
    

    中间件函数的执行是串行的,即按顺序执行的,因此引入中间件的顺序至关重要

    // this middleware will not allow the request to go beyond it
    app.use(function (req, res, next) {
      res.send("Hello World"); // 这里中间件已经把响应发过去了,res 就不会再通过 http 动作到达路由了
    });
    
    // requests will never reach this route
    app.get("/", function (req, res) {
      res.send("Welcome");
    });
    

    Error-handling middleware

    上述的中间件函数的参数都只有三个,req/res/next,而进行错误处理的中间件接收四个参数,必须要提供四个参数才能用函数签名表明它是一个错误处理的中间件函数。

    app.use(function (err, req, res, next) {
      console.error(err.stack);
      res.status(500).send("Something broke!");
    });
    

    app.set()

    此外该 app 还能拥有 settings 设置属性,可通过 app.set(key, value) 设置,set 也可以设置普通变量。

    注意:但子 app 不继承父 app 拥有默认值的 settings,但会继承父 app 中不是默认值的 settings。(例外:子 app 会继承 trust proxy,即使是默认值;子 app 在生产环境中不会继承 view cache,即当NODE_ENV 为 production 时)

    case sensitive routing:路由是否大小写敏感

    env:环境模式,生产/开发

    etag:设置 res 的 ETag

    jsonp callback name:默认 JSONP 的回调函数名称(默认为 "callback")

    json escape:是否在如 res.json/res.jsonp/res.send 等传输到客户端的信息中对 html 敏感字符(</>/&)转义

    json replacer:传给 JSON.stringify 的 replacer 参数

    json spaces:传给 JSON.stringify 的 spaces 参数

    query parser:参数解析器,simple 版基于 node 内置的 querystring,extended 版基于 qs

    strict routing:严格路由(冗余/是否会被容忍)

    subdomain offset:url 中分隔子域从第几个点开始

    trust proxy:可信的代理,使用的话 Express 会尝试获取前端使用的代理 IP 地址,基于 proxy-addr

    views:一个目录或一个目录数组,用于提供可访问的 views

    view cache:是否允许 view 模板编译缓存

    view engine:对不同拓展名的 view 页面使用的分析引擎

    x-powered-by:允许 x-powered-by 的 http 头部

    Request

    req 对象用来表现 http 请求,它有请求的查询字符串、参数、正文、http 头部等,按照约定,在 express 中称为 req(响应称为 res)。。

    属性)req.app

    对于正在使用当前中间件函数的那个 Express 应用实例的引用。

    // index.js
    app.get("/viewdirectory", require("./mymiddleware.js"));
    
    // mymiddleware.js
    module.exports = function (req, res) {
      res.send("The views directory is " + req.app.get("views"));
    };
    

    req.baseUrl

    路由实例挂载在的那个 URL 路径。

    const greet = express.Router();
    
    greet.get("/jp", function (req, res) {
      console.log(req.baseUrl); // /greet
      res.send("Konichiwa!");
    });
    
    app.use("/greet", greet); // load the router on '/greet'
    

    req.body

    包含通过请求体 submit 的一系列键值对。req.body 默认是 undefined 的,需要使用 body-parsing 的中间件(body-parser 或 multer)才会填充 req.body 的内容。

    const app = require("express")();
    const bodyParser = require("body-parser");
    const multer = require("multer"); // v1.0.5
    const upload = multer(); // for parsing multipart/form-data
    
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
    
    app.post("/profile", upload.array(), function (req, res, next) {
      console.log(req.body);
      res.json(req.body);
    });
    

    req.cookies

    当使用了 cookie-parser 中间件时,这个属性会等于请求中包含的 cookie,默认值为 {}。对签名的 cookie 需要使用 req.signedCookies

    // Cookie: name=tj
    console.dir(req.cookies.name);
    // => "tj"
    

    req.fresh

    判断客户端缓存的内容还新不新鲜,还新鲜返回 true,不新鲜返回 false。当客户端使用 Cache-Control: no-cache 的头部,则请求要求服务端必须发送新的内容,因此 req.fresh 为不新鲜(需要更新的内容)。

    req.host

    包含 http 头部的 host(主机名+端口)属性。

    req.hostname

    包含 http 头部的 hostname(主机名)属性。

    req.ip

    包含请求的 remote IP。

    req.ips

    trust proxy 不为 false,这个属性包含一系列的放在 X-Forwarded-For 头部的 IP 地址。

    req.method

    包含该请求的 http 动作。

    req.originalUrl

    类似 req.url(但 req.url 不是原生的 Express 属性,而是继承自 node 的 http 模块),但是它包含了原始的请求 URL,不会被重写(而 req.url 会在作为子 app 挂载的时候被重写)

    req.originalUrl = req.baseUrl + req.path

    app.use("/admin", function (req, res, next) {
      // GET 'http://www.example.com/admin/new'
      console.dir(req.originalUrl); // '/admin/new'
      console.dir(req.baseUrl); // '/admin'
      console.dir(req.path); // '/new'
      next();
    });
    

    req.params

    请求如果使用了动态路由(如 /user/:userId),动态部分可以被 req.params 访问到。

    // GET /user/tj
    console.dir(req.params.name);
    // => "tj"
    

    req.path

    返回请求的路径部分(相对的),从中间件中调用的话,req.path 是不包含挂载点的路径的。

    // example.com/users?sort=desc
    console.dir(req.path);
    // => "/users"
    

    req.protocol

    请求的协议,http 或者 https。

    req.query

    请求的查询字符串对象,需要使用中间件(query-parser 或 qs)。注意: req.query 来自用户输入,要防范 XSS。

    req.route

    包含一个当前匹配的路径对象字符串。

    app.get("/user/:id?", function userIdHandler(req, res) {
      console.log(req.route);
      res.send("GET");
    });
    
    /**
     * output:
     *
     * { path: '/user/:id?',
     *   stack:
     *    [ { handle: [Function: userIdHandler],
     *        name: 'userIdHandler',
     *        params: undefined,
     *        path: undefined,
     *        keys: [],
     *        regexp: /^\/?$/i,
     *        method: 'get' } ],
     *   methods: { get: true } }
     **/
    

    req.secure

    等价于 req.protocol === 'https'

    req.signedCookies

    使用 cookie-parser 中间件,属性包含一个带签名的 cookie(防范 CSRF)

    // Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
    console.dir(req.signedCookies.user);
    // => "tobi"
    

    req.stale

    表明请求是否“过时”,是 req.fresh 的反义词。

    req.fresh === !req.stale 为 true。

    req.subdomains

    一个包含所有次域名的数组,默认的起点是 2,可以通过 settings 的 subdomain offset 更改。

    // Host: "tobi.ferrets.example.com"
    console.dir(req.subdomains);
    // => ["ferrets", "tobi"]
    

    req.xhr

    是否用 xhr 进行请求,请求中头部的 X-Requested-With 等于 "XMLHttpRequest" 时为 true。

    方法)req.accepts(types)

    判断请求的 Accept 头部能否满足 types 的要求,返回第一个最好地满足要求的 types。

    // Accept: text/*, application/json
    req.accepts("html");
    // => "html"
    req.accepts("text/html");
    // => "text/html"
    req.accepts(["json", "text"]);
    // => "json"
    req.accepts("application/json");
    // => "application/json"
    
    // Accept: text/*, application/json
    req.accepts("image/png");
    req.accepts("png");
    // => false
    

    req.acceptsCharsets(charset [, ...])

    判断请求的 Accept-Charset 头部能否满足 charset(们)的要求,返回第一个合格的 charset。

    req.acceptsEncodings(encoding [, ...])

    判断请求的 Accept-Encoding 头部能否满足 charset(们)的要求,返回第一个合格的 encoding。

    req.acceptsLanguages(lang [, ...])

    判断请求的 Accept-Language 头部能否满足 charset(们)的要求,返回第一个合格的 lang。

    req.get(field)

    返回特定的 HTTP 头部对应键的那个值,不分大小写。

    req.get("Content-Type");
    // => "text/plain"
    
    req.get("content-type");
    // => "text/plain"
    
    req.get("Something");
    // => undefined
    

    req.is(type)

    断请求体的 Content-Type 头部能否满足 type 的要求。如果请求没有 body,返回 null;不满足 type 返回 false。

    // With Content-Type: text/html; charset=utf-8
    req.is("html"); // => 'html'
    req.is("text/html"); // => 'text/html'
    req.is("text/*"); // => 'text/*'
    
    // When Content-Type is application/json
    req.is("json"); // => 'json'
    req.is("application/json"); // => 'application/json'
    req.is("application/*"); // => 'application/*'
    
    req.is("html");
    // => false
    

    req.range(size[, options])

    请求的 Range 头部解析器。range 用于断点续传,响应成功 206 Partial Content,范围出错 416 Range Not Satisfiable。

    size 表明资源的最大值,options 中的 combine 属性表明重复/相邻的 range 是否合并,默认 false。

    返回负数表示错误:-1 为范围出错,-2 为头部格式错误。

    // parse header from request
    const range = req.range(1000);
    
    // the type of the range
    if (range.type === "bytes") {
      // the ranges
      range.forEach(function (r) {
        // do something with r.start and r.end
      });
    }
    

    Response

    res 是一个 http 响应,它是由 Express 应用对 HTTP 请求的响应。

    res 对象是一个 Node 自身 response 响应的升级版,因此支持所有的 Node response 内置属性和方法。

    属性)res.app

    和 req.app 一样,返回调用当前中间件的一个 Express 的实例对象引用。

    res.headersSent

    表明 app 是否在响应中发送过 http 头部了。

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

    res.locals

    一个包含响应的本地变量的对象,仅在 views 渲染使用时且请求/响应的生命周期未结束时使用。可用于暴露很多 request-level 的信息,比如请求的路径名,认证的用户、用户的设置等。

    app.use(function (req, res, next) {
      res.locals.user = req.user;
      res.locals.authenticated = !req.user.anonymous;
      next();
    });
    

    方法)res.append(field [, value])

    将 value 添加到 http 头部中的 field 键对应值的末尾。

    res.append("Link", ["<http://localhost/>", "<http://localhost:3000/>"]);
    res.append("Set-Cookie", "foo=bar; Path=/; HttpOnly");
    res.append("Warning", "199 Miscellaneous warning");
    

    res.attachment([filename])

    添加附件,设置 http 响应的 Content-Disposition 头部为 "attachment",如果提供了 filename,会根据后缀来通过 res.type() 设置 Content-Type。

    res.attachment();
    // Content-Disposition: attachment
    
    res.attachment("path/to/logo.png");
    // Content-Disposition: attachment; filename="logo.png"
    // Content-Type: image/png
    

    res.cookie(name, value [, options])

    设置响应的 cookie,将 value 的值赋给 name。

    res.cookie("name", "tobi", {
      domain: ".example.com",
      path: "/admin",
      secure: true,
    });
    res.cookie("rememberme", "1", {
      expires: new Date(Date.now() + 900000),
      httpOnly: true,
    });
    

    res.clearCookie(name [, options])

    消除 cookie 中名为 name 的键值对。

    res.download(path [, filename] [, options] [, fn])

    将位于 path 的文件作为 "attachment" 进行传输。

    res.download("/report-12345.pdf");
    
    res.download("/report-12345.pdf", "report.pdf");
    
    res.download("/report-12345.pdf", "report.pdf", function (err) {
      if (err) {
        // Handle error, but keep in mind the response may be partially-sent
        // so check res.headersSent
      } else {
        // decrement a download credit, etc.
      }
    });
    

    res.end([data] [, encoding])

    最快速度地终止响应。需要用数据来响应,应该使用 res.send()res.json()

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

    res.format(object)

    根据 http 请求对象的 Accept 头部来进行不同的处理。

    res.format({
      "text/plain": function () {
        res.send("hey");
      },
    
      "text/html": function () {
        res.send("<p>hey</p>");
      },
    
      "application/json": function () {
        res.send({ message: "hey" });
      },
    
      default: function () {
        // log the request and respond with 406
        res.status(406).send("Not Acceptable");
      },
    });
    

    当请求的头部中 Accept 的值为 "application/json" 或者 "*/json" ,输出结果为 { "message": "hey" }

    res.get(field)

    返回一个键为 field 的 http 响应头部的值。

    res.get("Content-Type");
    // => "text/plain
    

    res.json([body])

    传输一个 JSON 响应。

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

    res.jsonp([body])

    传输一个用 JSONP 方式包起 JSON 的响应,其实就是 res.json() 包了一层 callback。

    res.jsonp(null);
    // => callback(null)
    
    res.jsonp({ user: "tobi" });
    // => callback({ "user": "tobi" })
    
    res.status(500).jsonp({ error: "message" });
    // => callback({ "error": "message" })
    

    res.links(links)

    拼合成响应的头部中的 link

    res.links({
      next: "http://api.example.com/users?page=2",
      last: "http://api.example.com/users?page=5",
    });
    

    res.location(path)

    设置响应的头部中的 location

    res.location("/foo/bar");
    res.location("http://example.com");
    res.location("back");
    

    path 值设置为 "back" 时,它等于请求头部中的 Referer(即“你从哪里来”),如果没有 Referer 的话,就会等于根目录 "/"。

    res.redirect([status,] path)

    重定向到一个基于 path 的 URL,还可以指定响应的状态码。

    res.redirect("/foo/bar");
    res.redirect("http://example.com");
    res.redirect(301, "http://example.com");
    res.redirect("../login");
    

    res.render(view [, locals] [, callback])

    渲染一个 view 并且发送渲染过后的 html 到客户端,如果指定了 callback,该 html 需要手动发送响应。

    // send the rendered view to the client
    res.render("index");
    
    // if a callback is specified, the rendered HTML string has to be sent explicitly
    res.render("index", function (err, html) {
      res.send(html);
    });
    
    // pass a local variable to the view
    res.render("user", { name: "Tobi" }, function (err, html) {
      // ...
    });
    

    res.send([body])

    发送一个 HTTP 响应,body 可以是 Buffer 对象、字符串、对象、布尔类型、数组。它会根据 body 的类型自动设置响应的 Content-Type 头部。

    res.send(Buffer.from("whoop"));
    res.send({ some: "json" });
    res.send("<p>some html</p>");
    res.status(404).send("Sorry, we cannot find that!");
    res.status(500).send({ error: "something blew up" });
    

    res.sendFile(path [, options] [, fn])

    向 path 发送文件,使用绝对路径,会自动根据文件名后缀设置 Content-Type 头部。

    app.get("/file/:name", function (req, res, next) {
      const options = {
        root: path.join(__dirname, "public"),
        dotfiles: "deny",
        headers: {
          "x-timestamp": Date.now(),
          "x-sent": true,
        },
      };
    
      const fileName = req.params.name;
      res.sendFile(fileName, options, function (err) {
        if (err) {
          next(err);
        } else {
          console.log("Sent:", fileName);
        }
      });
    });
    

    res.sendStatus(statusCode)

    设置响应的 HTTP 状态码,并将其相关文字信息作为响应体。

    res.sendStatus(200); // equivalent to res.status(200).send('OK')
    res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
    res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
    res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
    

    res.set(field [, value])

    赋值给响应的 http 头部对应的键,又被叫做 res.header(field [, value])

    res.set("Content-Type", "text/plain");
    
    res.set({
      "Content-Type": "text/plain",
      "Content-Length": "123",
      ETag: "12345",
    });
    

    res.status(code)

    给响应设置 http 状态,可链式调用。

    res.status(403).end();
    res.status(400).send("Bad Request");
    res.status(404).sendFile("/absolute/path/to/404.png");
    

    res.type(type)

    设置响应的 Content-Type 头部,会自动调用 mime.lookup() 找到对匹配的那个 MIME 类型。

    res.type(".html"); // => 'text/html'
    res.type("html"); // => 'text/html'
    res.type("json"); // => 'application/json'
    res.type("application/json"); // => 'application/json'
    res.type("png"); // => image/png:
    

    res.vary(field)

    设置响应的 Vary 头部。

    res.vary("User-Agent").render("docs");
    

    起源地下载网 » 【学习笔记】Express 的 API 有哪些?这里全了

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元