express()
express()Used to create an Express application.express()The method isexpressa top-level method exported by the module.
var express = require('express');
var app = express();
Methods
express.static(root, [options])
express.staticIt is the only built-in middleware in Express. It is based on theserver-staticmodule and is responsible for hosting static assets in Express applications.rootis the root directory where static assets reside.optionsis optional and supports the following properties:
| Property | Description | Type | Default value |
|---|---|---|---|
| dotfiles | Whether to respond to dotfiles. Available values are "allow", "deny", and "ignore". | String | "ignore" |
| etag | Enable or disable etag. | Boolean | true |
| extensions | Set file extension fallback. | Boolean | true |
| index | Send directory index file. Set to false to not send. | Mixed | "index.html" |
| lastModified | Set the file's last modification time in the system toLast-Modifiedheader. Possible values arefalseandtrue。 | Boolean | true |
| maxAge | Set in the Cache-Control headermax-ageattribute, with precision in milliseconds (ms) or ams formatstring. | Number | 0 |
| redirect | When the requested pathname is a directory, redirect to a trailing "/". | Boolean | true |
| setHeaders | Method for setting headers when responding to static file requests. | Funtion |
If you want more details about using middleware, you can refer toServing static files in Express。
Application()
appThe app object generally represents an Express application. By calling the top-levelexpress()method exported by the Express module to create it:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('hello world!');
});
app.listen(3000);
The app object has the following methods:
- Routes HTTP requests; for details seeapp.METHODandapp.paramthese two examples.
- Configures middleware; for details seeapp.route。
- Renders HTML views; for details seeapp.render。
- Registers template engines; for details seeapp.engine。
It also has some property settings that can change the application's behavior. For more information, seeApplication settings。
Properties
app.locals
The app.locals object is a JavaScript object, and its properties are application-local variables.
app.locals.title // => 'My App' app.locals.email // => 'me@myapp.com'
Once set,app.localsits property values will last throughout the entire life cycle of the application. In contrast,res.localsit is only valid within the life cycle of the current request.
In the application, you can use these local variables when rendering templates. They are very useful for providing templates with helpful methods andapplevel data. Throughreq.app.locals(seereq.app), Locals can be used in middleware.
app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';
app.mountpath
app.mountpathThe property is the path pattern on which a sub-application is mounted.
A sub-application is anexpressinstance, which can be used as a route handler to handle requests.
var express = require('express');
var app = express(); // the main app
var admin = express(); // the sub app
admin.get('/', function(req, res) {
console.log(admin.mountpath); // /admin
res.send('Admin Homepage');
});
app.use('/admin', admin); // mount the sub app
It is similar to the req object'sreq.baseUrlproperty is similar, except that req.baseUrl is the matched URL path, not the matched pattern. If a sub-application is mounted on multiple path patterns, app.mountpath is a list of mount path pattern items, as shown in the following example.
var admin = express();
admin.get('/', function (req, res) {
console.log(admin.mountpath); // [ '/adm*n', '/manager' ]
res.send('Admin Homepage');
});
var secret = express();
secret.get('/', function (req, res) {
console.log(secret.mountpath); // /secr*t
res.send('Admin Secret');
});
admin.use('/secr*t', secret); // load the 'secret' router on '/secr*t', on the 'admin' sub app
app.use(['/adm*n', '/manager'], admin); // load the 'admin' router on '/adm*n' and '/manager', on the parent app
Events
app.on('mount', callback(parent))
When a sub-application is mounted on a parent application, the mount event is emitted. The parent application object is passed as a parameter to the callback method.
var 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);
Methods
app.all(path, callback[, callback ...]
app.allThe method is similar to the standardapp.METHOD()methods, except that it matches all HTTP verbs. It is very useful for mapping global logic handling to a specific prefix, or for unconditional matching. For example, if you put the following content before all other route definitions, it requires all routes from this point on to require authentication and automatically load a user. Remember that these callbacks are not necessarily endpoints:loadUserAfter completing a task, you can callnext()method to continue matching subsequent routes.
app.all('*', requireAuthentication, loadUser);Or this equivalent form:
app.all('*', requireAuthentication);
app.all('*', loadUser);
Another example is a global whitelist method. This example is very similar to the previous one, except that it only restricts paths starting with/apithe prefix.
app.all('/api/*', requireAuthentication);
app.delete(path, callback[, callback ...])
RoutesHTTP DELETErequests to specific paths with special callback methods. For more information, seerouting guide.next('router')to bypass the remaining route callbacks. You can use this mechanism to set preconditions for a route. If the request cannot satisfy the current route's handling conditions, you can pass control to subsequent routes.
app.delete('/', function(req, res) {
res.send('DELETE request to homepage');
});
app.disable(name)
Sets the boolean setting namednameto the valuefalse, wherenameYesapp settings tableis one of the properties in app settings. Callingapp.set('foo', false)and callingapp.disable('foo')are equivalent.
app.disable('trust proxy');
app.get('trust proxy');
// => false
app.disabled(name)
Returnstrueif the boolean settingnameis disabled (set to false)false, wherenameYesapp settings tableis one of the properties in app settings.
app.disabled('trust proxy');
// => true
app.enable('trust proxy');
app.disabled('trust proxy');
// => false
app.enable(name)
Sets the boolean settingnameistrue, wherenameYes
app.enable('trust proxy');
app.get('trust proxy');
// => true
app.enabled(name)
Returnstrueif the boolean settingnameis enabled (set to true)true, wherenameYesapp settings tableis one of the properties in app settings.
app.enabled('trust proxy');
// => false
app.enable('trust proxy');
app.enabled('trust proxy');
// => true
app.engine(ext, callback)
Registers the callback of the given engine to render files with the ext extension.require()to load engines based on file extensions. For example, if you try to render afoo.jadefile, Express internally calls the following, and caches therequire()result for subsequent calls to speed up performance.
app.engine('jade', require('jade').__express);
Use the following method for those that do not provide an out-of-the-box.__expressmethod, or when you want to use a different template engine extension..htmlfile:
app.engine('html', require('ejs').renderFile);In this example, EJS provides a.renderFilemethod that satisfies the signature rules specified by Express:(path, options, callback), but remember that internally it is justejs.__expressan alias of, so you can directly use the.ejsextension.consolidate.jsThe library maps template engines in the following way, so they can work seamlessly with Express.
var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
app.get(name)
Gets the app setting namednamethe value of the app setting, wherenameYesapp settings tableis one of the properties in app settings.
app.get('title');
// => undefined
app.set('title', 'My Site');
app.get('title');
// => 'My Site'
app.get(path, callback [, callback ...])
RoutesHTTP GETrequests to specific paths with special callbacks. For more information, seerouting guide.next('router')to bypass the remaining route callbacks. You can use this mechanism to set preconditions for a route. If the request fails to satisfy the current route's handling conditions, pass control to subsequent routes.
app.get('/', function(req, res) {
res.send('GET request to homepage');
});
app.listen(port, [hostname], [backlog], [callback])
Binds the application to listen on the specified host and port. This method andNodeinhttp.Server.listen()are the same.
var express = require('express');
var app = express();
app.listen(3000);
By callingexpress()the returnedappis actually a JavaScriptFunction, designed to be passed as a callback toNode HTTP serversto handle requests. In this way, it can easily provide HTTP and HTTPS versions based on the same code, so the app does not inherit from these (it is just a simple callback).
var express = require('express');
var https = require('https');
var http = require('http');
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
The app.listen() method is a convenience method as shown below (only for the HTTP protocol):
app.listen = function() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
app.METHOD(path, callback [, callback ...])
Routes an HTTP request,METHODis the HTTP method of the request, such asGET,PUT,POSTetc. Note that they are lowercase. So, the actual methods areapp.get(),app.post(),app.put()etc. Below is a complete table of the methods.
For more information, seerouting guide.
|
|
|
If using the above methods results in invalid JavaScript variable names, you can use bracket notation, for example,app['m-search']('/', function ...
You can provide multiple callback functions, which behave like middleware, except that these callbacks can, by callingnext('router')bypass the remaining route callbacks. You can use this mechanism to set preconditions for a route. If the request does not satisfy the current route's handling conditions, pass control to subsequent routes.
This API documentation describes the commonly used HTTP methodsapp.get(),app.post,app.put(),app.delete()as separate items. However, the other methods listed above work in exactly the same way.
app.all()is a special routing method that is not one of the methods defined in the HTTP protocol. It loads middleware for a path, and it is valid for all request methods.
app.all('/secret', function (req, res) {
console.log('Accessing the secret section...');
next(); // pass control to the next handler
});
app.param([name], callback)
Adds callback triggers to route parameters, wherenameis the parameter name or an array of parameter names,functionis the callback method. The parameters of the callback method, in order, arerequest object,response object,next middleware,parameter valueandparameter name.nameIf it is an array, the callback triggers are registered in the order in which each parameter is declared in the array. Also, for parameters other than the last one, calling next() in their callbacksnext()to call the callback of the next declared parameter. For the last parameter, call it in the callback.next()will call the next middleware in the currently processed route, ifnameis just astringthen it is the same as it (that is, if there is only one parameter, then it is the last parameter, same as the last parameter in the array). For example, when:userappears in the route path, you can map the logical processing of user loading to automatically providereq.userto this route, or validate the input parameters.
app.param('user', function(req, res, next, id) {
User.find(id, function(error, user) {
if (err) {
next(err);
}
else if (user){
req.user = user;
} else {
next(new Error('failed to load user'));
}
});
});
ForParamroutes defined by callbacks, they are local. They are not inherited by mounted apps or routes. Therefore, defined onapponParamcallbacks only take effect whenappthe route on ... has this route parameter, then they take effect.
When definingparamon routes,paramcallbacks are all called first; they are called once and only once in a request-response cycle, even if multiple routes match, as in the following example:
app.param('id', function(req, res, next, id) {
console.log('CALLED ONLY ONCE');
next();
});
app.get('/user/:id', function(req, res, next) {
console.log('although this matches');
next();
});
app.get('/user/:id', function(req, res) {
console.log('and this mathces too');
res.end();
});
When GET /user/42, the following result is obtained:
CALLED ONLY ONCE although this matches and this matches too
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, next) {
console.log('and this matches too');
res.end();
});
When executing GET /user/42/3, the result is as follows:
CALLED ONLY ONCE with 42 CALLED ONLY ONCE with 3 although this matches and this mathes too
described in the following sectionapp.param(callback)has been deprecated since v4.11.0.
By passing only one callback argument toapp.param(name, callback)method,app.param(naem, callback)the behavior of the method will be completely changed. This callback argument is a custom method aboutapp.param(name, callback)what behavior it should have. This method must accept two parameters and return a middleware. The first parameter of this callback is the URL parameter name to capture, and the second parameter can be any JavaScript object that may be used when implementing the returned middleware. The middleware returned by this callback determines the behavior to take when the URL contains this parameter. In the following example,app.param(name, callback)the parameter signature has been modified toapp.param(name, accessId). Instead of accepting a parameter name and callback,app.param()it now accepts a parameter name and a number.
var express = require('express');
var app = express();
app.param(function(param, option){
return function(req, res, next, val) {
if (val == option) {
next();
}
else {
res.sendStatus(403);
}
}
});
app.param('id', 1337);
app.get('/user/:id', function(req, res) {
res.send('Ok');
});
app.listen(3000, function() {
console.log('Ready');
});
In this example, the app.param(name, callback) parameter signature remains the same as before, but it is replaced with a middleware that defines a custom data-type checking method to verify the correctness of the user id type.
app.param(function(param, validator) {
return function(req, res, next, val) {
if (validator(val)) {
next();
}
else {
res.sendStatus(403);
}
}
});
app.param('id', function(candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate);
});
When using regular expressions, do not use.. For example, you cannot use/user-.+/to captureuser-gami, instead use[\\s\\S]or[\\w\\>W]to replace (just as/user-[\\s\\S]+/)。
//captures '1-a_6' but not '543-azser-sder' router.get('/[0-9]+-[[\\w]]*', function); //captures '1-a_6' and '543-az(ser"-sder' but not '5-a s' router.get('/[0-9]+-[[\\S]]*', function); //captures all (equivalent to '.*') router.get('[[\\s\\S]]*', function);
app.path()
through this method you can obtainappthe canonical path, which is astring。
var app = express()
, blog = express()
, blogAdmin = express();
app.use('/blog', blog);
app.use('/admin', blogAdmin);
console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
If the app is mounted in a complex way, then the behavior of this method will also be complex: a better way is to use req.baseUrl to obtain the app's canonical path.
app.post(path, callback, [callback ...])
Routes HTTP POST requests to a special path with special callbacks. For more information, see the [routing guide](http://expressjs.com/guide/routing.html).
You can provide multiple callback functions that behave like middleware, except that these callbacks can bypass the remaining route callbacks by calling next('router'). You can use this mechanism to set some preconditions for a route; if the request does not satisfy the current route's handling conditions, pass control to the subsequent routes.
app.post('/', function(req, res) {
res.send('POST request to homepage')
});
app.put(path, callback, [callback ...])
RoutesHTTP PUTrequests to a special path with special callbacks. For more information, seerouting guide。
You can provide multiple callback functions that behave like middleware, except that these callbacks can, by callingnext('router')bypass the remaining route callbacks. You can use this mechanism to set some preconditions for a route; if the request does not satisfy the current route's handling conditions, pass control to the subsequent routes.
app.put('/', function(req, res) {
res.send('PUT request to homepage');
});
app.render(view, [locals], callback)
Throughcallbackcallback returns anviewHTML text obtained after rendering. It can accept an optional parameter that contains theviewlocal data needed. This method is similar tores.render(),except that it cannot send the rendered HTML text to the client。
willapp.render()Treat it as a utility method that can generate rendered view strings. Inres.render()internally, it usesapp.render()to render views.
If view caching is enabled, the local variable cache will be retained. If you want to cache views during development, set it totrue. In production, view caching is enabled by default.
app.render('email', function(err, html) {
// ...
});
app.render('email', {name:'Tobi'}, function(err, html) {
// ...
});
app.route(path)
Returns a singleton route instance, on which you can then apply middleware for various HTTP actions. Useapp.route()to avoid duplicate route names (e.g., typo errors) -- the meaning is that you should useapp.router()this singleton method to avoid multiple route instances for the same path.
var 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.set(name, value)
Assigns value to the setting name, where name isApplication settingsone of the properties in it. For a Boolean property, calling app.set('foo', ture) is equivalent to calling app.enable('foo'). Similarly, calling app.set('foo', false) is equivalent to calling app.disable('foo').
You can use app.get() to get the set value:
app.set('title', 'My Site');
app.get('title'); // 'My Site'
Application Settings
Ifnameis one of the application settings, it will affect the behavior of the application. The application settings are listed below.
| Property | Type | Value | Default |
|---|---|---|---|
| case sensitive routing | Boolean | Enable case sensitivity. | Not enabled. For/Fooand/foothe handling is the same. |
| env | String | Environment mode. | process.env.NODEENV(NODEENV environment variable) or 'development' |
| etag | Varied | SetETagresponse header. For possible values, seeetag options table. More aboutHTTP ETag header。 | weak |
| jsonp callback name | String | Specifies the default JSONP callback name. | ?callback= |
| json replacer | String | JSONP callback | null |
| json spaces | Number | When this value is set, JSON strings beautified with indented spaces are sent. | Disabled |
| query parser | Varied | Set the value tofalseto disablequery parser, or setsimple,extended, or you can implement your ownquery stringparsing function.simpleBased onNodenativequeryparsing,querystring。 | "extend" |
| strict routing | Boolean | Enable strict routing. | Not enabled. For/fooand/foo/route handling is the same. |
| subdomain offset | Number | The number of dot-separated parts of the host to remove to access subdomains | 2 |
| trust proxy | Varied | Indicatesappbehind a reverse proxy, usex-Forwarded-*to determine the connection and client IP address. Note:X-Forwarded-*The header is easy to spoof, so detecting the client's IP address is unreliable.trust proxyDisabled by default. When enabled, Express attempts to obtain the connected client's IP address through the front-facing proxy or a series of proxies.req.ipsThe property contains an array of connected client IP addresses. To enable it, set the value defined intrust proxy options tablethe value defined below.trust proxyThe implementation of the setting usesproxy-addrpackage. If you want more information, you can consult its documentation | Disable |
| views | String or Array | viewthe directory or directory array where it is located. If it is an array, it will be looked up in the order in the array.view。 | process.cwd() + '/views' |
| view cache | Boolean | Enable view template compilation cache. | Enabled by default in production. |
| view engine | String | When omitted, the default engine is used for the extension. | |
| x-powered-by | Boolean | EnableX-Powered-By:ExpressHTTP header | true |
trust proxyoption settingseeExpress behind proxiesfor more information.
| Type | Value |
|---|---|
| Boolean |
If it istrue, the client IP address is taken as theX-Forwarded-*leftmost entry of the header. If it isfalse, it can be understood thatappis directly connected to the Internet, and the client IP address is derived fromreq.connection.remoteAddress。falseis the default setting. |
| IP addresses |
An IP address, subnet, or a group of IP addresses, and delegated subnets. Below is a list of preconfigured subnet names.
Use any of the following methods to set the IP address:
app.set('trust proxy', 'loopback') // specify a single subnet
app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address
app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array
When an IP address is specified, this IP address or subnet is excluded from the app that has this IP address or subnet set; the non-delegated address closest to the application server will be regarded as the client IP address. |
| Number |
Trust connections with hops less than or equal to n between the reverse proxy and the app as the client. |
| Function |
Custom delegated proxy trust mechanism. If you use this, make sure you know what you are doing.
app.set('trust proxy', function (ip) {
if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs
else return false;
})
|
etagSetting option ETagthe implementation of the feature usesetagpackage. If you need more information, you can consult its documentation.
| Type | Value |
|---|---|
| Boolean |
Set totrue, enables weak ETag. This is the default setting. Setfalse, disables all ETags. |
| String | If it isstrong, enables strong ETag. If it isweak, enablesweak ETag。 |
| Function |
a custom ETag method implementation. If you use this, make sure you know what you are doing.
app.set('etag', function (body, encoding) {
return generateHash(body, encoding); // consider the function is defined
})
|
app.use([path,], function [, function...])
Mountsmiddlewaremethod to the path. If the path is not specified, it defaults to '/'.
A route will match any path if the path is immediately followed by '/' after the route's set path. For example:app.use('/appale', ...)will match '/apple', '/apple/images', '/apple/images/news', etc.
in the middlewarereq.originalUrlYesreq.baseUrlandreq.pathThe combination, as shown in the example below.
app.use('/admin', function(req, res, next) { // GET 'http://www.example.com/admin/new' console.log(req.originalUrl); // '/admin/new' console.log(req.baseUrl); // '/admin' console.log(req.path);// '/new' });
After mounting a middleware at a path, the middleware will be executed whenever the prefix of the requested path matches the route path. Since the default path is/, if the middleware is mounted without specifying a path, this middleware will be executed for every request.
// this middleware will be executed for every request to the app.
app.use(function(req, res, next) {
console.log('Time: %d', Date.now());
next();
});
Middleware methods are processed in order, so the order in which middleware is included is very important.
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
});
// this middleware will never reach this route
app.use('/', function(req, res) {
res.send('Welcome');
});
The path can be a string representing a path, a path pattern, a regular expression matching a path, or an array of these.
Below are simple examples of paths.
| Type | Example |
|---|---|
| Path |
// will match paths starting with /abcd
app.use('/abcd', function (req, res, next) {
next();
})
|
| Path Pattern |
// will match paths starting with /abcd and /abd
app.use('/abc?d', function (req, res, next) {
next();
})
// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on
app.use('/ab+cd', function (req, res, next) {
next();
})
// will match paths starting with /abcd, /abxcd, /abFOOcd, /abbArcd and so on
app.use('/ab\*cd', function (req, res, next) {
next();
})
// will match paths starting with /ad and /abcd
app.use('/a(bc)?d', function (req, res, next) {
next();
})
|
| Regular Expression |
// will match paths starting with /abc and /xyz
app.use(/\/abc|\/xyz/, function (req, res, next) {
next();
})
|
| Array |
// will match paths starting with /abcd, /xyza, /lmn, and /pqr
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) {
next();
})
|
The method can be a middleware method, a series of middleware methods, an array of middleware methods, or a combination of them. Since router and app implement the middleware interface, you can use them like any other middleware method.
| Usage | Example |
|---|---|
| Single middleware | You can locally define and mount a middleware.app.use(function (req, res, next) {
next();
})
A router is valid middleware.var router = express.Router();
router.get('/', function (req, res, next) {
next();
})
app.use(router);
An Express app is valid middleware.var subApp = express();
subApp.get('/', function (req, res, next) {
next();
})
app.use(subApp);
|
| A series of middleware | For the same mount path, you can mount more than one middleware.var r1 = express.Router();
r1.get('/', function (req, res, next) {
next();
})
var r2 = express.Router();
r2.get('/', function (req, res, next) {
next();
})
app.use(r1, r2);
|
| Array | Logically, use an array to organize a set of middleware. If you pass an array of middleware as the first or only parameter, then you need to specify the mount path.var r1 = express.Router();
r1.get('/', function (req, res, next) {
next();
})
var r2 = express.Router();
r2.get('/', function (req, res, next) {
next();
})
app.use('/', [r1, r2]);
|
| Combination | You can combine all of the following methods to mount middleware.function mw1(req, res, next) { next(); }
function mw2(req, res, next) { next(); }
var r1 = express.Router();
r1.get('/', function (req, res, next) { next(); });
var r2 = express.Router();
r2.get('/', function (req, res, next) { next(); });
var subApp = express();
subApp.get('/', function (req, res, next) { next(); });
app.use(mw1, [mw2, r1, r2], subApp);
|
The following are some examples of using the express.static middleware in an Express app.
Serve static assets located in the public directory under the app directory:
// GET /style.css etc app.use(express.static(__dirname + '/public'));
In/staticMount the middleware at the path to provide static asset hosting, only when the request starts with/staticas a prefix.
// GET /static/style.css etc.
app.use('/static', express.static(express.__dirname + '/public'));
Turn off logging for static asset requests by loading the logger middleware after setting up the static middleware.
app.use(express.static(__dirname + '/public')); app.use(logger());
Serve static assets from different paths, but./publicthe path is more easily matched than others:
app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/files')); app.use(express.static(__dirname + '/uploads'));
Request
reqThe object represents an HTTP request and has properties that hold data from the request, such asquery string,parameters,body,HTTP headersetc. In this document, by convention, this object is always referred to asreq(the HTTP response is referred to asres), but their actual names are determined by the parameters of the callback method where they are used.
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
Actually, you can also write it like this:
app.get('/user/:id', function(request, response) {
response.send('user' + request.params.id);
});
Properties
InExpress 4In,req.filesBy default,reqit is no longer available in the object.req.filesobject to obtain uploaded files, you can use amultipart-handling(multipart-handling toolkit) middleware, such asbusboy,multer,formidable,multipraty,connect-multipartyorpez。
req.app
This property holdsexpressa reference to the app instance, which can be used as middleware.
If you follow this pattern, you create a module that exports a middleware, and this middleware is only in your main filerequire()it, then this middleware can throughreq.appobtain the Express instance.
// 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
The URL path on which a router instance is mounted.
var greet = express.Router();
greet.get('/jp', function(req, res) {
console.log(req.baseUrl); // greet
res.send('Konichiwa!');
});
app.use('/greet', greet);
Even if you use a path pattern or an array of path patterns to load the router,baseUrlthe property returns the matched string, not the route pattern. In the following example,greetthe router is loaded on two path patterns.
app.use(['/gre+t', 'hel{2}o'], greet); // load the on router on '/gre+t' and '/hel{2}o'
When a request path is/greet/jp,baseUrlYes/greet, when a request path is/hello/jp,req.baseUrlYes/hello。 req.baseUrlandappthe object'smountpathproperty is similar, exceptapp.mountpathreturns the path matching pattern.
req.body
The request body contains key-value pairs of submitted data. By default, it isundefined, when you use, for example,body-parserandmulterthis kind of parsingbodydata middleware, it is populated.body-parsermiddleware to populatereq.body。
var app = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');// v1.0.5
var 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
When using the cookie-parser middleware, this property is an object containing cookies sent with the request. If the request does not carry cookies, its value is {}.
// Cookie: name=tj req.cookies.name // => "tj"
For more information, questions, or concerns, seecookie-parser。
req.fresh
Indicates whether the request is fresh. It is the opposite ofreq.staleis the opposite.cache-controlthe request header does not haveno-cachedirective and any one of the following conditions istrue, then it istrue:
- if-modified-sincethe request header is specified, andlast-modifiedthe request header is equal to or earlier thanmodifiedthe response header.
- if-none-matchthe request header is*。
- if-none-matchthe request header, after being parsed into its directives, isetagnot equal to the value of the response header.
ps: Role of If-None-Match: If-None-Match works together with ETag. The working principle is to add ETag information in the HTTP Response. When the user requests the resource again, If-None-Match information (the value of ETag) will be added to the HTTP Request. If the server verifies that the resource's ETag has not changed (the resource has not been updated), it will return a 304 status to tell the client to use the local cache file. Otherwise, it will return a 200 status with the new resource and Etag. Using such a mechanism will improve website performance.
req.fresh // => true
req.hostname
contains the value derived fromHostthe HTTP headerhostname。
Whentrust proxyWhen the setting is set to an enabled value,X-Forwarded-Hostthe header is used instead ofHost. This header can be set by the client or a proxy.
// Host: "example.com" req.hostname // => "example.com"
req.ips
Whentrust proxyWhen the setting is set to an enabled value, this property contains an array ofX-Forwarded-ForIP addresses specified in the request header. Otherwise, it contains an empty array. This header can be set by the client or a proxy.
For example, ifX-Forwarded-ForYesclient,proxy1,proxy2,req.ipsthen it is["clinet", "proxy1", "proxy2"], whereproxy2is the farthest downstream.
req.originalUrl
req.urlis not a nativeExpressproperty; it inherits fromNode's http module。
This property is very similar toreq.url; however, it retains the original request URL, allowing you to freely redirectreq.urlto internal routes. For example,app.use()ofmountingthe feature can redirectreq.urlto the mount point.
// GET /search?q=something req.originalUrl // => "/search?q=something"
req.params
An object containing properties that correspond one-to-one with the parameter names named in the route. For example, if you have/user/:nameroute,namethe property can be used asreq.params.name. The default value of this object is{}。
// GET /user/tj req.params.name // => "tj"
When you use regular expressions to define route rules, the capture group combinations generally usereq.params[n], wherenis the ordinal number of the capture group. This rule is applied to unnamed wildcard matches, such as/file/*the route:
// GET /file/javascripts/jquery.js req.params[0] // => "javascripts/jquery.js"
req.path
Contains the path part of the request URL.
// example.com/users?sort=desc req.path // => "/users"
When called in a middleware, the mount point is not included inreq.path. You can refer toapp.use()for more information.
req.protocol
The protocol of the request, usuallyhttp, and when TLS encryption is enabled, it ishttps。
Whentrust proxyWhen the setting is set to an enabled value, if theX-Forwarded-Protoheader exists, it will be trusted and used. This header can be set by the client or a proxy.
req.ptotocol // => "http"
req.query
An object that, for eachquery stringparameter in the route, assigns a property. If there is noquery string, it is an empty object.{}。
// GET /search?q=tobi+ferret req.query.q // => "tobi ferret" // GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse req.query.order // => "desc" req.query.shoe.color // => "blue" req.query.shoe.type // => "converse"
req.route
The currently matched route, which is a string. For example:
app.get('/user/:id?', function userIdHandler(req, res) {
console.log(req.route);
res.send('GET')
})
The output of the previous segment is:
{ path:"/user/:id?"
stack:
[
{ handle:[Function:userIdHandler],
name:"userIdHandler",
params:undefined,
path:undefined,
keys:[],
regexp:/^\/?$/i,
method:'get'
}
]
methods:{get:true}
}
req.secure
A boolean value. If a TLS connection is established, then it istrue. Equivalent to:
'https' == req.protocol;
req.signedCookies
When usingcookie-parsermiddleware, this property contains the signed value sent with the requestcookies, and this property gets the unsigned value that can be used directly. The signedcookiesis stored in a different object to reflect the developer's intent; otherwise, a malicious attack can be applied toreq.cookievalue (it is very easy to be deceived). Remember, signing acookieis not hiding or encrypting it; it is simply to prevent tampering (because the encryption used for signing is private). If no signedcookieis sent, then this property defaults to{}。
// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 req.signedCookies.user // => "tobi"
For more information, questions, or concerns, seecookie-parser。
req.stale
Indicates whether the request isstale(stale), which isreq.freshthe opposite. For more information, seereq.fresh。
req.stale // => true
req.subdomains
An array of subdomains in the request's domain.
// Host: "tobi.ferrets.example.com" req.subdomains // => ["ferrets", "tobi"]
req.xhr
A boolean value. IfX-Requested-Withthe value ofXMLHttpRequest, then it istrue, which indicates that the request was sent by a client library, such asjQuery。
req.xhr // => true
Methods
req.accepts(types)
Checks whether the specified content type is accepted, based on the request's Accept HTTP header. This method returns the best match. If there is no match, it returns undefined (in this case, the server should return 406 and "Not Acceptable").
The type value can be a single MIME type string (such as application/json), an extension such as json, a comma-separated list, or an array. For a list or array, this method returns the best item (if any).
// Accept: text/html
req.accepts('html');
// => "html"
// 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');
// => undefined
// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
// => "json"
For more information, or if you have questions or concerns, seeaccepts。
req.acceptsCharsets(charset[, ...])
Returns the first configured charset in the specified character set, based on the request'sAccept-CharsetHTTP header. If no matching charset is found, returns false. For more information, or if you have questions or concerns, seeaccepts。
req.acceptsEncodings(encoding[, ...])
Returns the first accepted encoding of the specified encoding set, based on the request'sAccept-EncodingHTTP header. If no matching encoding is found in the specified encoding set, returns false. For more information, or if you have questions or concerns, seeaccepts。
req.acceptsLanguages(lang [, ...])
Returns the first accepted language of the specified language set, based on the request'sAccept-LanguageHTTP header. If no matching language is found in the specified language set, returns false. For more information, or if you have questions or concerns, seeaccepts。
req.get(field)
Returns the content of the specified request HTTP header field (case-insensitive).ReferrerandRefererThe field content is interchangeable.
req.get('Content-type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something')
// => undefined
It isan alias of req.header(field).
req.is(type)
If the incoming request'sContent-typeheader field matches the parametertypegivenMIME type, then it returnstrue. Otherwise, it returnsfalse。
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true
// When Content-Type is application/json
req.is('json');
req.is('application/json');
req.is('application/*');
// => true
req.is('html');
// => false
For more information, or if you have questions or concerns, seetype-is。
req.param(naem, [, defaultValue])
Deprecated. Use, where appropriate,req.params,req.bodyorreq.query。
Returns the current parameter'snamevalue.
// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
Lookup is performed in the following order:
- req.params
- req.body
- req.query
Optionally, you can specify adefaultValueto set a default value if this parameter cannot be found in any of the request objects.
Directly viareq.params,req.body,req.queryobtaining it should be clearer - unless you are certain about the input of each object.Body-parserThe middleware must be loaded if you usereq.param(). For details, seereq.body。
Response
resobject represents, when an HTTP request arrives,Expressthe HTTP response returned by the app. In this documentation, by convention, this object is always abbreviated asres(the HTTP request is abbreviated asreq), but their actual names are determined by the parameters of the callback method in which they are used.
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
For example:
app.get('/user/:id', function(request, response) {
response.send('user' + request.params.id);
});
Properties
res.app
Writing it this way is the same:
This property holds a reference to the Express app instance, which can be used in middleware.
res.headersSent
res.app and the req.app property in the request object are the same.</p>
app.get('/', function(req, res) {
console.log(res.headersSent); // false
res.send('OK'); // send之后就发送了头部
console.log(res.headersSent); // true
});
res.locals
A Boolean property indicating whether this response has already sent HTTP headers.app.localsAn object that contains variables local to this request's response, and therefore its variables are only available to view rendering within the cycle of this request's response (if there are views). In other respects, it and
are the same.
app.use(function(req, res, next) {
res.locals.user = req.user;
res.locals.authenticated = !req.user.anonymous;
next();
});
Methods
res.append(field [, value])
This parameter is very useful for exposing request-level information, such as request path, authenticated user, user settings, etc.ExpresxsThe res.append() method is
only supported in versions 4.11.0 and above.fieldto the specifiedvalueHTTP header field, append the specified value.valueIf this header has not been set, then usevalueto create this header.
can be a string or an array.res.append()Note: Afterapp.set()calling
res.append('Lind', ['<http://localhost>', '<http://localhost:3000>']);
res.append('Set-Cookie', 'foo=bar;Path=/;HttpOnly');
res.append('Warning', '199 Miscellaneous warning');
res.attachment([filename])
the function will reset the previously set value.Content-DispositionSets the HTTP response'sfilenameheader content to 'attachment'. If providedres.type(), then viaContent-Typeobtaining the extension to setContent-Disposition, and set
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])
content to 'filename=parameter'.nameandvalueofcookie,valueThe
parameter can be a string or an object converted to a JSON string.
| options is an object that can have the following properties. | Property | Type |
|---|---|---|
| domain | String | Description |
| expires | Date | Sets the domain name for the cookie. The default is your app's domain. |
| httpOnly | Boolean | The cookie's expiration time, in GMT format. If not specified or set to 0, a new cookie is generated. |
| maxAge | String | A flag that this cookie can only be obtained by the web server. |
| path | String | is a convenient option for setting the expiration time; it is the millisecond value from the current time to the expiration time./。 |
| secure | Boolean | The cookie's path. The default value isHTTPSIndicates that this cookie can only be used by |
| signed | Boolean | protocol. |
Indicates that this cookie should be signed.optionsWhat res.cookie() does is based on the providedSet-Cookieparameter to setoptionsheader. If none of theRFC6265options are specified, then the default value is
specified in
res.cookie('name', 'tobi', {'domain':'.example.com', 'path':'/admin', 'secure':true});
res.cookie('remenberme', '1', {'expires':new Date(Date.now() + 90000), 'httpOnly':true});
Usage examples:
res.cookie('rememberme', '1', {'maxAge':90000}, "httpOnly":true);
maxAge is a convenient option for setting the expiration time, calculated in milliseconds from the current time. The following example has the same effect as the second one above.
res.cookie('cart', {'items':[1, 2, 3]});
res.cookie('cart', {'items':[1, 2, 3]}, {'maxAge':90000});
You can pass an object as the value parameter. It will then be serialized as a JSON string and parsed by the bodyParser() middleware.
res.cookie('name', 'tobi', {'signed':true});
res.clearCookie(name [,options])
When using the cookie-parser middleware, this method also supports signed cookies. Simply include the signed option set to true when setting options. Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.nameAccording to the specifiedoptionsclears the corresponding cookie. For more aboutres.cookie()。
res.cookie('name', 'tobi', {'path':'/admin'});
res.clearCookie('name', {'path':'admin'});
res.download(path, [,filename], [,fn])
object, seepathTransfersContent-Dispositionthe specified file as an attachment. Usually, the browser prompts the user to download. By default,paththe 'filename=' parameter in the header isfilename(usually appears in the browser's dialog). By specifying
parameter to override the default value.fnWhen an error occurs or the transfer is complete, this method will callres.sendFile()the specified callback method. This method uses
res.download('/report-12345.pdf');
res.download('/report-12345.pdf', 'report.pdf');
res.download('report-12345.pdf', 'report.pdf', function(err) {
// Handle error, but keep in mind the response may be partially-sent
// so check res.headersSent
if (err) {
} else {
// decrement a download credit, etc.
}
});
res.end([data] [, encoding])
to transfer the file.NodeEnds the response process. This method actually comes fromresponse.end() method of http.ServerResponse。
the core module, specificallyres.send()andres.json()used to quickly end the request without any data. If you need to send data, you can use
res.end(); res.status(404).end();
res.format(object)
methods like these.AcceptPerforms content negotiation, based on the request object's406Accept HTTP header specified acceptable content. It uses req.accepts() to select a handler to serve the request; these handlers are sorted by quality value. If this header is not specified, the first method is called by default. When there is no match, the server returnsdefault'Not Acceptable', or invokes
Content-Typethe callback.res.set()The response header is set when a callback method is selected. However, you can change it in this method using methods such asres.type()。
or{"message":"hey"}The following example will reply withAcceptwhen the request object's*/*header is set to 'application/json' or '*/json' (but if it is
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() {
res.status(406).send('Not Acceptable');
}
})
, then the response will be 'hey').
res.format({
text:function() {
res.send('hey');
},
html:function() {
res.send('<p>hey</p>');
},
json:function() {
res.send({message:'hey'});
}
})
res.get(field)
In addition to normalized MIME types, you can also use extensions to map these types to avoid verbose implementations:fieldReturns
res.get('Content-Type');
// => "text/plain"
res.json([body])
the specified HTTP response header. Matching is case-sensitive.res.send()Sends a JSON response. This method is the same as passing an object or an array as a parameter tonull,undefinedmethod. However, you can use this method to convert other values to JSON, such as
res.json(null);
res.json({user:'tobi'});
res.status(500).json({error:'message'});
res.jsonp([body])
. (Although these are technically invalid JSON).
res.jsonp(null)
// => null
res.jsonp({user:'tobi'})
// => {"user" : "tobi"}
res.status(500).jsonp({error:'message'})
// => {"error" : "message"}
Sends a JSON response and supports JSONP. This method has the same effect as res.json(), except that it supports JSONP callbacks in its options.jsonp callback nameBy default, the JSONP callback method is simply written as callback. It can be
overridden via the setting.
// ?callback=foo
res.jsonp({user:'tobo'})
// => foo({"user":"tobi"})
app.set('jsonp callback name', 'cb')
// ?cb=foo
res.status(500).jsonp({error:'message'})
// => foo({"error":"message"})
res.links(links)
The following are some examples using JSONP responses, using the same code:links,linksJoins the links
res.links({
next:'http://api.example.com/users?page=2',
last:'http://api.example.com/user?page=5'
});
provided as properties of the passed-in parameter; the joined content is used to populate the response's Link HTTP header.
Link:<http://api.example.com/users?page=2>;rel="next", <http://api.example.com/users?page=5>;rel="last"
res.location(path)
Result:LocationSets the response'spathHTTP header to the specified
res.location('/foo/bar');
res.location('http://example.com');
res.location('back');
Whenpathparameter.backWhen the parameter isReferer, it has special meaning; it specifies the URL as the request object's
header-specified URL. If not specified in the request, then it is '/'.LocationExpress passes the specified URL string as the reply to the browser in the response'sbackheader value, without detection or manipulation, except forlocationthis parameter. The browser will redirect the user toRefererthe URL set by, orbackthe URL of (
res.redirect([status,] path)
parameter case).pathRedirects to the URL derived from the specifiedHTTP status codestatusURL, and the specifiedstatus. If you do not specify
res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');
, the status code defaults to '302 Found'.
res.redirect('http://google.com');</p><p>
重定向也可以相对于主机的根路径。比如,如果程序的路径为<strong>http://example.com/admin/post/new</strong>,那么下面将重定向到<strong>http://example.com/admim</strong>:</p>
<pre>res.redirect('/admin');The redirect can also be a complete URL, to redirect to a different site.http://example.com/blog/admin/The redirect can also be relative to the current URL. For example, from/(note the trailing /http://example.com/blog/admin/post/new。
res.redirect('post/new');), the following will redirect tohttp://example.com/blog/admin(without trailing/), redirectpost/new, will redirect tohttp://example.com/blog/post/new. If you think the above is confusing, you can treat path segments as directories (with '/') or files, which is fine. Relative path redirects are also allowed. If your current path ishttp://example.com/admin/post/new, the following operation will redirect tohttp://example.com/admin/post:
res.redirect('..');backRedirects the request toreferer, when norefereris provided, the default is/。
res.redirect('back');
res.render(view [, locals] [, callback])
Render a view, and then send the rendered HTML document to the client. Optional parameters are:
- locals, an object that defines the local property attributes of the view.
- callback, a callback function. If this parameter is provided,renderthe method will return the error and the rendered template, and will not automatically send the response. When an error occurs, you can call thenext(err)method inside this callback.
Local variable caching enables view caching. To cache views in the development environment, you need to manually set it to true; view caching is enabled by default in the production environment.
// send the rendered view to the client
res.render('index');
// if a callback is specified, the render 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])
Sends an HTTP response.
bodyThe parameter can be aBufferobject, a string, an object, or an array. For example:
res.send(new Buffer('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' });
For general non-streaming requests, this method can perform many useful tasks: for example, it automatically assigns the Content-Length HTTP response header (unless previously defined), and also supports automatic HEAD and HTTP cache updates.
When the parameter is a Buffer object, this method sets the Content-Type response header to application/octet-stream, unless provided in advance, as shown below:
res.set('Content-Type', 'text/html');
res.send(new Buffer('<p>some html</p>'));
When the parameter is a string, this method sets the Content-Type response header to text/html:
res.send('<p>some html</p>');
When the parameter is an object or an array, Express represents it in JSON format:
res.send({user:'tobi'});
res.send([1, 2, 3]);
res.sendFile(path [, options] [, fn])
res.sendFile()fromExpress v4.8.0Support began.
Transferpaththe specified file. Set theContent-TypeHTTP header based on the file extension. Unless inoptionsthere is a setting regardingroot,pathmust be an absolute path to the file.optionsparameter details:
| Property | Description | Default value | Available versions |
|---|---|---|---|
| maxAge | Set theCache-Controlofmax-ageproperty, in milliseconds, or a string inms formatformat | 0 | |
| root | Root directory relative to the file name | ||
| lastModified | Set theLast-Modifiedheader to the last modified time of this file in the system. Setfalseto disable it. | Enable | 4.9.0+ |
| headers | An object containing file-related HTTP headers. | ||
| dotfiles | The option of whether to support dotfiles. Possible values are "allow", "deny", "ignore" | "ignore" |
When the transfer is complete or an error occurs, this method calls thefncallback method. If this callback parameter is specified and an error occurs, the callback method must explicitly handle the response process by ending the request-response cycle or passing control to the next route.
The following is an example of using all parameters withres.sendFile():
app.get('/file/:name', function(req, res, next) {
var options = {
root:__dirname + '/public',
dotfile:'deny',
headers:{
'x-timestamp':Date.now(),
'x-sent':true
}
};
var fileName = req.params.name;
res.sendFile(fileName, options, function(err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('sent', fileName);
}
});
});
res.sendFile provides fine-grained support for file serving, as illustrated in the following example:
app.get('/user/:uid/photos/:file', function(req, res) {
var uid = req.params.uid
, file = req.params.file;
req.user.mayViewFilesFrom(uid, function(yes) {
if (yes) {
res.sendFile('/upload/' + uid + '/' + file);
}
else {
res.status(403).send('Sorry! you cant see that.');
}
});
})
For more information, or if you have questions or concerns, refer tosend。
res.sendStatus(statusCode)
Sets the response object'sHTTP status codeisstatusCodeand sendsstatusCodethe corresponding string representation of as the response body.
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')
If an unsupported status is specified, the HTTP status is still set tostatusCodeand the string of this code is used as the body.
res.sendStatus(2000); // equivalent to res.status(2000).send('2000');
res.set(field [, value])
Sets the HTTP header of the response objectfieldisvalue. To set multiple values at once, you can pass an object as the parameter.
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type':'text/plain',
'Content-Length':'123',
'ETag':'123456'
})
It has the same effect asres.header(field [,value]).
res.status(code)
Use this method to set the HTTP status of the response object. It is in Noderesponse.statusCodea chainable alias of.
res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');
res.type(type)
The app will set theContent-TypeMIME type of the HTTP header, if this settypecan bemime.lookupparsed into the correctContent-Type. Iftypecontains/characters, the app will directly setContent-Typeistype。
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)
Adds the Vary response header when there is no Vary response header.
Note: the meaning of Vary is to tell proxy servers/caches/CDNs how to determine whether requests are the same. The combinations in Vary are the basis for servers/caches/CDNs to determine this. For example, if Vary contains User-Agent, then even for the same request, if a user opens a page with IE and then opens it again with Firefox, the CDN/proxy will consider them different pages. If Vary does not contain User-Agent, the CDN/proxy will consider them the same page and directly return the cached page to the user without requesting the page from the web server again. In layman's terms, it is equivalent tofieldusing it as a cache key to determine whether the cache is hit.
res.vary('User-Agent').render('docs');
Router
Arouterobject is a standalone instance of middleware and routing. You can think of it as a "mini-application" that has the ability to operate on middleware and routing methods. EveryExpressapp has a built-in app router.app.use()method's parameter or as another route'suse()parameter.expressobject has aRouter()method, and you can useRouter()to create a newrouterobject.
res.vary('User-Agent').render('docs');
Router([options])
As follows, you can create a route:
var router = express.Router([options]);
optionsThe parameter can specify the behavior of the route, with the following options:
| Property | Description | Default value | Availability |
|---|---|---|---|
| caseSensitive | Whether to distinguish case | Not enabled by default. Treat/Fooand/foothe same. | |
| mergeParams | Preserve the parent route'sres.params. If parent route parameters conflict with child route parameters, child route parameters take precedence. | false | 4.5.0+ |
| strict | Enables strict routing. | Not enabled by default,/fooand/foo/are treated the same by routing. |
You can treatrouteras an app, on which you can add middleware and HTTP routing methods (such asget,put,postetc.).
// invoked for any requests passed to this router
router.use(function(req, res, next) {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
// ..
});
You can mount a router at a specific root URL, so you can place your various routes in different files or even mini programs.
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);
Methods
router.all(path, [callback, ...] callback)
This method is the same as therouter.METHOD()method, except that this method matches all HTTP actions.
This method is very useful for mapping global logic to a specific path prefix or arbitrary matching. For example, if you place the route shown below before other routes, it will require all routes from this point on to perform verification operations and automatically load user information. Remember, these global logic operations do not need to end the request-response cycle:loaduserYou can perform a task, and then callnext()to pass the execution flow to subsequent routes.
router.all('*', requireAuthentication, loadUser);Equivalent form:
router.all('*', requireAuthentication)
router.all('*', loadUser);
This is an example of a whitelist global feature. This example is similar to the previous one, but it only applies to paths starting with/api:
router.all('/api/*', requireAuthentication);
router.METHOD(path, [callback, ...] callback)
router.METHOD()The method provides routing methods inExpress, whereMETHODis one of the HTTP methods, such asGET,PUT,POSTetc., but therouterMETHOD in is lowercase. Therefore, the actual methods arerouter.get(),router.put(),router.post()etc.
You can provide multiple callback functions, which behave like middleware, except that these callbacks can callnext('router')to bypass the remaining route callbacks. You can use this mechanism to set preconditions for a route. If the request does not satisfy the current route's handling conditions, pass control to the subsequent routes.
The following snippet may illustrate the simplest route definition. Express converts the path string into a regular expression for internal matching of incoming requests. When matching, it does not considerQuery strings, for example, "GET /" will match the following route, and so will "GET /?name=tobi".
router.get('/', function(req, res) {
res.send('Hello World');
});
If you have special restrictions on the path to match, you can use regular expressions. For example, the following can match "GET /commits/71dbb9c" and "GET /commits/71bb92..4c084f9".
router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res) {
var from = req.params[0];
var to = req.params[1];
res.send('commit range ' + from + '..' + to);
});
router.param(name, callback)
Adds callback triggers to route parameters, wherenameis the parameter name,functionis the callback method. The callback method's parameters, in order, are the request object, the response object, the next middleware, the parameter value, and the parameter name. Althoughnameis technically optional, it is not recommended after Express V4.11.0 (see below).
Unlikeapp.param(),router.param()does not accept an array as route parameters.
For example, when:userappears in the route path, you can map user loading logic to automatically providereq.userto this route, or validate the input parameters.
router.param('user', function(req, res, next, id) {
User.find(id, function(error, user) {
if (err) {
next(err);
}
else if (user){
req.user = user;
} else {
next(new Error('failed to load user'));
}
});
});
ForParamcallback-defined routes, they are local. They are not inherited by the mounted app or router. Therefore, defined onroutertheparamcallbacks only if onrouteronly takes effect when the route on it has this route parameter.
When definingparamon the route,paramcallbacks are the first to be called, and they will be called once and only once in a request-response cycle, even if multiple routes match, as in the following example:
router.param('id', function(req, res, next, id) {
console.log('CALLED ONLY ONCE');
next();
});
router.get('/user/:id', function(req, res, next) {
console.log('although this matches');
next();
});
router.get('/user/:id', function(req, res) {
console.log('and this mathces too');
res.end();
});
When GET /user/42 is requested, the following result is obtained:
CALLED ONLY ONCE although this matches and this matches too
Described in the following sectionrouter.param(callback)has been deprecated since v4.11.0.
By passing only one callback parameter to therouter.param(name, callback)method,router.param(naem, callback)the behavior of the method will be completely changed. This callback parameter is a custom method that definesrouter.param(name, callback)what behavior it should have. This method must accept two parameters and return a middleware.
The first parameter of this callback is the name of the URL parameter to capture, and the second parameter can be any JavaScript object, which may be used when implementing the returned middleware. The middleware returned by this callback method determines the behavior to take when the URL contains this parameter.
In the following example,router.param(name, callback)the parameter signature has been modified torouter.param(name, accessId). The replacement accepts a parameter name and a callback,router.param()and now accepts a parameter name and a number.
var express = require('express');
var app = express();
var router = express.Router();
router.param(function(param, option){
return function(req, res, next, val) {
if (val == option) {
next();
}
else {
res.sendStatus(403);
}
}
});
router.param('id', 1337);
router.get('/user/:id', function(req, res) {
res.send('Ok');
});
app.use(router);
app.listen(3000, function() {
console.log('Ready');
});
In this example, the router.param(name. callback) parameter signature remains the same as before, but it is replaced with a middleware that defines a custom data type detection method to verify the correctness of the user id type.
router.param(function(param, validator) {
return function(req, res, next, val) {
if (validator(val)) {
next();
}
else {
res.sendStatus(403);
}
}
});
router.param('id', function(candidate) {
return !isNaN(parseFloat(candidate)) && isFinite(candidate);
});
router.route(path)
Returns a singleton route instance, on which you can then apply middleware for various HTTP actions. Userouter.route()to avoid duplicate route names (e.g. typo errors) -- the meaning is to userouter.route()this singleton method to avoid multiple route instances for the same path.
Built on therouter.param()example above, the following code shows how to userouter.route()to specify handlers for various HTTP methods.
var router = express.Router();
router.param('user_id', function(req, res, next, id) {
// sample user, would actually fetch from DB, etc...
req.user = {
id:id,
name:"TJ"
};
next();
});
router.route('/users/:user_id')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
next();
})
.get(function(req, res, next) {
res.json(req.user);
})
.put(function(req, res, next) {
// just an example of maybe updating the user
req.user.name = req.params.name;
// save user ... etc
res.json(req.user);
})
.post(function(req, res, next) {
next(new Error('not implemented'));
})
.delete(function(req, res, next) {
next(new Error('not implemented'));
})
This method reuses a single/usrs/:userid path to add various HTTP methods.
router.use([path], [function, ...] function)
For the optionalpathparameter, mount the given middleware method to the specified path. If thepathparameter is not specified, the default value is/.app.use(). This method is similar toapp.use()for more information.
Middleware is like a plumbing pipe. The request starts at the first middleware you define and flows down the middleware stack, processing the request if the path matches.
var express = require('express');
var app = express();
var router = express.Router();
// simple logger for this router`s requests
// all requests to this router will first hit this middleware
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
})
// this will only be invoked if the path starts with /bar form the mount ponit
router.use('/bar', function(req, res, next) {
// ... maybe some additional /bar logging ...
next();
})
// always be invoked
router.use(function(req, res, next) {
res.send('hello world');
})
app.use('/foo', router);
app.listen(3000);
For middleware functions, the mounted path is stripped and invisible. The main impact of this feature is that for different paths, mounting the same middleware may not require code changes, even though its prefix has changed.
The order in which you define middleware using router.use() is important. Middleware are called in order, so the order determines the priority of the middleware. For example, logging is usually the first middleware you use, so that every request is recorded.
var logger = require('morgan');
router.use(logger());
router.use(express.static(__dirname + '/public'));
router.use(function(req, res) {
res.send('Hello');
});
Now, to support that you don't want to log static file requests, but want to continue logging those routes and middleware defined afterlogger(). You can simply movestatic()to the front to solve this:
router.use(express.static(__dirname + '/public'));
router.use(logger());
router.use(function(req, res){
res.send('Hello');
});
Another concrete example is hosting static files from different paths. You can put./publicin front to get higher priority:
app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/files')); app.use(express.static(__dirname + '/uploads'));
router.use()The method also supports named parameters, so that your mount point can use named parameters for preloading with respect to other routes, which is very beneficial.
Original address: https://github.com/bajian/express_api_4.x_chinese