中间件
Express 3.x 包含许多内置的中间件函数,可用于处理诸如解析请求主体、处理 cookies 等常见任务。这些中间件函数可作为 Express 模块的属性使用,并可以通过 app.use() 添加到你的应用中。
🌐 Express 3.x includes a number of built-in middleware functions that can be used to handle common tasks such as parsing request bodies, handling cookies, and more. These middleware functions are available as properties on the Express module and can be added to your application using app.use().
basicAuth()
基本身份验证中间件,将用户名填充到 req.user 中。
🌐 Basic Authentication middleware, populating req.user
with the username.
简单的用户名和密码:
🌐 Simple username and password:
app.use(express.basicAuth('username', 'password'));回调验证:
🌐 Callback verification:
app.use( express.basicAuth(function (user, pass) { return user === 'tj' && pass === 'wahoo'; }));异步回调验证,接受 fn(err, user),在这种情况下,req.user 将是传入的用户对象。
🌐 Async callback verification, accepting fn(err, user),
in this case req.user will be the user object passed.
app.use( express.basicAuth(function (user, pass, fn) { User.authenticate({ user: user, pass: pass }, fn); }));bodyParser()
请求体解析中间件,支持 JSON、urlencoded 和 multipart 请求。这个中间件只是 json()、urlencoded() 和 multipart() 中间件的一个封装器。
🌐 Request body parsing middleware supporting JSON, urlencoded,
and multipart requests. This middleware is simply a wrapper
for the json(), urlencoded(), and
multipart() middleware.
app.use(express.bodyParser());
// is equivalent to:app.use(express.json());app.use(express.urlencoded());app.use(express.multipart());为了安全起见,如果你的应用不需要文件上传,最好禁用它。为此,只使用所需的中间件,即不要使用 bodyParser 和 multipart() 中间件:
🌐 For security sake, it’s better to disable file upload if your application
doesn’t need it. To do this, use only the needed middleware, i.e. don’t use
the bodyParser and multipart() middleware:
app.use(express.json());app.use(express.urlencoded());如果你的应用需要文件上传,你应该进行设置
🌐 If your application needs file upload you should set up
处理那些文件的策略
。
compress()
使用 gzip / deflate 压缩响应数据。该中间件应放置在堆栈中“高”位置,以确保所有响应都可以被压缩。
🌐 Compress response data with gzip / deflate. This middleware should be placed “high” within the stack to ensure all responses may be compressed.
app.use(express.logger());app.use(express.compress());app.use(express.methodOverride());app.use(express.bodyParser());cookieParser()
解析 Cookie 头字段并用以 cookie 名称为键的对象填充 req.cookies。你可以通过传入一个 secret 字符串来选择启用签名 cookie 支持。
🌐 Parses the Cookie header field and populates req.cookies
with an object keyed by the cookie names. Optionally you may enabled
signed cookie support by passing a secret string.
app.use(express.cookieParser());app.use(express.cookieParser('some secret'));cookieSession()
提供基于 cookie 的会话,并填充 req.session。
此中间件接受以下选项:
🌐 Provides cookie-based sessions, and populates req.session.
This middleware takes the following options:
keyCookie 名称默认为connect.sesssecret防止 Cookie 被篡改cookie会话 cookie 设置,默认为{ path: '/', httpOnly: true, maxAge: null }proxy在设置安全 cookie 时信任反向代理(通过 “x-forwarded-proto”)
app.use(express.cookieSession());要清除 cookie,只需在响应之前将会话分配为 null:
🌐 To clear a cookie simply assign the session to null before responding:
req.session = null;csrf()
CSRF保护中间件。
🌐 CSRF protection middleware.
默认情况下,这个中间件会生成一个名为“_csrf”的令牌,应当添加到修改状态的请求中,例如隐藏的表单字段、查询字符串等。这个令牌会与 req.csrfToken() 进行验证。
🌐 By default this middleware generates a token named “_csrf”
which should be added to requests which mutate
state, within a hidden form field, query-string etc. This
token is validated against req.csrfToken().
默认的 value 函数会检查由 bodyParser() 中间件生成的 req.body、由 query() 生成的 req.query,以及 “X-CSRF-Token” 头字段。
🌐 The default value function checks req.body generated
by the bodyParser() middleware, req.query generated
by query(), and the “X-CSRF-Token” header field.
此中间件需要会话支持,因此应添加在 session() 之下的某个位置。
🌐 This middleware requires session support, thus should be added
somewhere below session().
directory()
目录服务中间件,用于提供指定的 path。
此中间件可以与 static() 配合使用来提供文件,提供一个功能齐全的文件浏览器。
🌐 Directory serving middleware, serves the given path.
This middleware may be paired with static() to serve
files, providing a full-featured file browser.
app.use(express.directory('public'));app.use(express.static('public'));此中间件接受以下选项:
🌐 This middleware accepts the following options:
hidden显示隐藏(点)文件。默认值为 false。icons显示图标。默认值为 false。filter将此过滤函数应用于文件。默认值为 false。