Middleware : Web middlewares

更新时间:
2024-03-04
下载文档

Middleware : Web middlewares

Middleware can achieve some specific functions. WebApp provides some important middleware.

User can use the following code to import the middlewares module.

var mw = require('middleware');

Support

The WebApp support middleware as follow:

middlewaredescription
cookieParserParse Cookie header and populate req.cookies with an object keyed by the cookie names.
queryParserParse Query strings to objects req.query and objects to strings.
authParserParse Basic authentication to objects req.auth.
serveStaticServe static files of app. serveStatic support as middleware constructor.
bodyParserParse incoming request bodies in a middleware before your handlers, available under the req.body property.
multerA middleware for handling multipart/form-data, which is primarily used for uploading files.
sessionUse session to identify the specific user.
morganA middleware for handling log.
BusboyA module for parsing incoming HTML form data.
jwtJSON Web Token middleware.
WebDAVWeb-based Distributed Authoring and Versioning.
historyMiddleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 history API.
eosEdgerOS middleware.

authParser

req.auth

  • {Object}

If the request includes basic authentication information, this object contains the following attributes:

  • name {String} User name.
  • pass {String} Password.

serveStatic

serveStatic(root[, options])

  • root {String} Root directory of serve files.
  • option {Object} See Options.

Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining req.url with the provided root directory. When a file is not found, this module will return to move on to the next middleware, allowing for stacking and fall-backs.

root can be an absolute path or a relative path, when it is a relative path, the current path is the current directory of the current process.

Options

The options list:

optionvalue typedefaultconfig header
acceptRangesBooleantrueAccept-Ranges
cacheControlBooleantrueCache-Control
dotfilesString--
etagBooleantrueETag
extensionsBoolean / Arrayfalse-
fallthroughBooleantrue-
immutableBooleanfalseCache-Control
indexArray['index.html']-
lastModifiedBooleantrueLast-Modified
maxAgeNumber / String2592000000Max-Age
setHeadersFunction--
highWaterMarkInteger--

The details of options as follow.

acceptRanges

Enable or disable accepting ranged requests, defaults to true. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header.

cacheControl

Enable or disable setting Cache-Control response header, defaults to true. Disabling this will ignore the immutable and maxAge options.

dotfiles

Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny").

  • 'allow' No special treatment for dotfiles.
  • 'deny' Deny a request for a dotfile and 403.
  • 'ignore' Pretend like the dotfile does not exist and 404.

The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot.

etag

Enable or disable etag generation, defaults to true.

extensions

Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. The first that exists will be served. Example: ['html', 'htm']. Default to false.

fallthrough

Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply return to your next middleware when this value is true. When this value is false, these errors (even 404s), will invoke .

Typically true is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files.

The value false can be used if this middleware is mounted at a path that is designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

Default to true.

immutable

Enable or disable the immutable directive in the Cache-Control response header, defaults to false. If set to true, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.

index

By default this mdule will send "index.html" files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

lastModified

Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value.

maxAge

Provide a max-age in milliseconds for http caching, defaults to 2592000000ms (1 Month). This can also be a string accepted by the ms module.

setHeaders

Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called as fn(res, path, stat), where the arguments are:

  • res the response object
  • path the file path that is being sent
  • stat the stat object of the file that is being sent

highWaterMark

Data transfer will be paused when the underlying io is blocked and the internal cache reaches highWaterMark. When the asynchronous io wakes up again and the internal cache is cleared, the data continues to transfer. default: 128KB

Examples

Serve files with http server

var http = require('http');
var socket = require('socket');
var serveStatic = require('middleware').serveStatic;

// Serve up public/ftp folder
var serve = serveStatic('/root/public/ftp', { 'index': ['index.html', 'index.htm'] });

// Create server
var server = http.createServer('http_ser', serve, 0, socket.sockaddr(socket.INADDR_ANY, 8000));

// Listen
server.start();

Serving using WebApp

Simple

This is a simple example of using WebApp.

var WebApp = require('webapp');
var socket = require('socket');
var serveStatic = require('middleware').serveStatic;

var app = WebApp.create('web_static', 0, socket.sockaddr(socket.INADDR_ANY, 8000));
app.use(serveStatic('/root/public/ftp', { 'index': ['default.html', 'default.htm'] }));
app.start();

Multiple roots

This example shows a simple way to search through multiple directories. Files are look for in public-optimized/ first, then public/ second as a fallback.

var WebApp = require('webapp');
var socket = require('socket');
var serveStatic = require('middleware').serveStatic;

var app = WebApp.create('web_static', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

app.use(serveStatic('/root/public-optimized'));
app.use(serveStatic('/root/public'));
app.start();

Different settings for paths

This example shows how to set a different max age depending on the served file type. In this example, HTML files are not cached, while everything else is for 1 day.

var WebApp = require('webapp');
var socket = require('socket');
var serveStatic = require('middleware').serveStatic;

var app = WebApp.create('web_static', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

app.use(serveStatic('/root/public', {
  maxAge: '1d',
  setHeaders: setCustomCacheControl
}));

app.start();

function setCustomCacheControl(res, path) {
  if (serveStatic.mime.lookup(path) === 'text/html') {
    // Custom Cache-Control for HTML files
    res.setHeader('Cache-Control', 'public, max-age=0');
  }
}

bodyParser

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

See bodyParser for details.

multer

multer is a middleware for handling multipart/form-data, which is primarily used for uploading files.

See multer for details.

session

Since HTTP is a stateless protocol, when the server needs to record the state of the user, it needs to use session to identify the specific user.

See session for details.

morgan

Morgan is a http request logger middleware. Morgan provides some default log formats, and users can also customize the log formats.

See morgan for details.

Busboy

A module for parsing incoming HTML form data. It support Readable stream for file.

See Busboy for details.

jwt

An implementation of JSON Web Tokens.

See jsonwebtokenopen in new window for details.

WebDAV

WebDAV (Web based Distributed Authoring and Versioning) is a communication protocol based on HTTP 1.1 protocol. It extends HTTP 1.1, and adds some new methods in addition to several HTTP standard methods such as GET, POST, HEAD, so that applications can directly read and write to the server, and supports locking and unlocking of write files.

See WebDAV for details. This feature is available in EdgerOS 1.9.1 and later.

history

Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 history API.

See history for details. This feature is available in EdgerOS 1.10.2 and later.

EOS

req.eos

  • {Object}

This object only exists in the EdgerOS App main web service, and the requested EdgerOS-related information can be obtained through this object, such as user information req.eos.user.

req.eos.user Object contains the following information:

  • acoid {String} EdgerOS user unique ID, also known as acoinfo ID.
  • nickname {String} Nickname of this user.

The following fields are valid in EdgerOS 1.9.8 and later versions:

  • req.eos.token {String} This field is the original token string.
  • req.eos.channel {String} Indicates the access source, 'local' means local access, 'cloud' means access through EdgerOS Cloud.
文档内容是否对您有所帮助?
有帮助
没帮助