Easy Tutorial
❮ 2021 Frontend Learnpath Android Tutorial Shader ❯

Express 4.x API Documentation

Category: Programming Technology

express()

express() is used to create an Express application. The express() method is the top-level function exported by the express module.

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

Methods

express.static(root, [options])

express.static is the only built-in middleware in Express. It is based on serve-static and is responsible for serving static assets in an Express application. The root parameter specifies the root directory from which to serve static assets. The options parameter is optional and supports the following properties:

Property Description Type Default
dotfiles Option for serving dotfiles. Possible values are "allow", "deny", and "ignore" String "ignore"
etag Enable or disable etag generation Boolean true
extensions Set file extension fallbacks Boolean true
index Sends the specified directory index file. Set to false to disable directory indexing. Mixed "index.html"
lastModified Set the Last-Modified header to the last modified date of the file on the OS. Possible values are false and true. Boolean true
maxAge Set the max-age property of the Cache-Control header in milliseconds or a string in ms format Number 0
redirect Redirect to trailing "/" when the pathname is a directory Boolean true
setHeaders Function for setting HTTP headers to serve with the file Function

For more details on using middleware, you can refer to Serving static files in Express.

Application()

The app object typically represents the Express application. It is created by calling the top-level express() method exported by the Express module:

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:

It also has properties that can change the behavior of the application. For more information, see Application settings.

Properties

app.locals

The app.locals object is a JavaScript object, and its properties are local variables within the application.

app.locals.title
// => 'My App'
app.locals.email
// => '[email protected]'

Once set, the value of app.locals properties persist throughout the life of the application, in contrast to res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. They are useful for providing utility functions and app-level data. Locals can be used in middleware via req.app.locals (see req.app).

app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = '[email protected]';

app.mountpath

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

A sub-app is an instance of express that can be used as a middleware 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.baseUrl property, except req.baseUrl is the matched URL path, not the matched patterns. If a sub-app is mounted on multiple path patterns, app.mountpath returns a list of patterns, 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))

The mount event is emitted on a sub-app when it is mounted on a parent app. The parent app is passed as a parameter to the callback function.

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 ...])

The app.all method is similar to the standard app.METHOD() methods, except it matches all HTTP verbs. It is useful for mapping global logic for specific path prefixes or arbitrary matches. For example, if you place the following at the top of all other route definitions, it requires that all routes from this point require authentication and automatically load a user. Note that these callbacks do not have to act as end points; loadUser can perform a task, then call next() to continue matching subsequent routes.

app.all('*', requireAuthentication, loadUser);

Or equivalently:

app.all('*', requireAuthentication);
app.all('*', loadUser);

Another example is white-listing specific routes. This example is similar to the previous one, but it restricts the path prefix to /api.

app.all('/api/*', requireAuthentication);

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

Routes an HTTP DELETE request to the specified path with the specified callback functions. For more information, see the routing guide. You can provide multiple callback functions that behave like middleware, except these callbacks can call next('router') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

app.delete('/', function(req, res) {
    res.send('DELETE request to homepage');
});

app.disable(name)

Sets the Boolean setting name to false, where name is one of the properties from the app settings table. Calling app.set('foo', false) is equivalent to calling app.disable('foo').

For example:

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

app.disabled(name)

Returns true if the Boolean setting name is disabled (false), where name is one of the properties from the app settings table.

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

app.enable(name)

Sets the Boolean setting name to true, where name is one of the properties from the app settings table.

app.enable('trust proxy');
app.get('trust proxy');
// => true

app.enabled(name)

Returns true if the Boolean setting name is enabled (true), where name is one of the properties from the app settings table.

app.enabled('trust proxy');
// => false
app.enable('trust proxy');
app.enabled('trust proxy');
// => true

app.engine(ext, callback)

Registers the given template engine callback as ext. By default, Express will require() the engine based on the file extension. For example, if you attempt to render a "foo.jade" file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.

app.engine('jade', require('jade').__express);

Use the following method for engines that do not provide a .__express out of the box, or if you wish to "map" a different extension to the template engine. For example, use the EJS template engine to render ".html" files:

app.engine('html', require('ejs').renderFile);

In this case, EJS provides a .renderFile method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally, so if you're using ".ejs" extensions you don't need to do anything. Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);

app.get(name)

Get the value of the setting name, where name is one of the strings in the app settings table. For example:

app.get('title');
// => undefined
app.set('title', 'My Site');
app.get('title');
// => 'My Site'

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

Routes an HTTP GET request to the specified path with the specified callback functions. For more information, see the routing guide. You can provide multiple callback functions that behave just like middleware, except that these callbacks can call next('router') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.

app.get('/', function(req, res) {
    res.send('GET request to homepage');
});

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

Binds and listens for connections on the specified host and port. This method is identical to Node's http.Server.listen().

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

The app returned by express() is actually a JavaScript Function, designed to be passed to Node's HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same codebase, as the app does not inherit from these (it is simply a 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 for the following (for HTTP only):

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

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

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on. See the routing guide for more information. Express supports the following routing methods corresponding to the HTTP methods of the same names:

| checkout<br> connect<br> copy<br> delete<br> get<br> head<br> lock<br> merge<br> mkactivity | mkcol<br> move<br> m-search<br> notify<br> options<br> patch<br> post<br> propfind<br> proppatch | purege<br> put<br> report<br> search<br> subscribe<br> trace<br> unlock<br> unsubscribe |

>

If using the above method causes an invalid JavaScript variable name, use bracket notation. For example, app['m-search']('/', function ...

You can provide multiple callback functions that behave just like middleware, except that these callbacks can call next('router') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, and then pass control to subsequent routes if there is no reason to proceed with the current route.

>

This API documentation lists the app.get(), app.post(), app.put(), and app.delete() methods as commonly used HTTP methods separately. However, the other methods listed above work in the same way.

app.all() is a special routing method that is not derived from any HTTP method. It loads middleware for a path 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, where name is the name of the parameter or an array of them, and function is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter, and the name of the parameter, in that order. If name is an array, the callback trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for parameters other than the last parameter, calling next() in the callback will call the callback for the next declared parameter. For the last parameter, calling next() will call the next middleware in place for the route currently being processed, if name is just a string, then it is the same as the last parameter. For example, when :user appears in a route path, you can map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

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'));
        }
    });
});

For routes defined on app where the param callback is defined, these callbacks are local. They are not inherited by mounted apps or routers. Hence, defined param callbacks will only be triggered by route parameters defined on app routes.

All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown 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 matches too');
    res.end();
});
console.log('and this matches 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 matches too

The app.param(callback) described in the following section is deprecated after v4.11.0.

By passing only a callback parameter to the app.param(name, callback) method, the behavior of the app.param(name, callback) method will be completely changed. This callback parameter is a custom method about how app.param(name, callback) should behave, which must accept two parameters and return a middleware. The first parameter of this callback is the parameter name to be captured in the URL, and the second parameter can be any JavaScript object, which may be used when implementing a middleware to be returned. The middleware returned by this callback method determines the behavior when the URL contains this parameter. In the following example, the parameter signature of app.param(name, callback) is modified to app.param(name, accessId). Instead of accepting a parameter name and a callback, app.param() 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 parameter signature of app.param(name, callback) remains the same, but it is replaced with a middleware that defines a custom data type checking method to check 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 capture user-gami, use [\s\S] or [\w\W] instead (like /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()

This method returns the canonical path of the app, which is a string.

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 very complexly, the behavior of this method can be complex as well. The better way to get the canonical path of the app is to use req.baseUrl.

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

Routes HTTP POST requests to the specified path with the specified callbacks. For more information, see the routing guide.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can call next('router') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, and then pass control to subsequent routes if there is no reason to proceed with the current route.

app.post('/', function(req, res) {
    res.send('POST request to homepage')
});

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

Routes HTTP PUT requests to the specified path with the specified callbacks. For more information, see the routing guide.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can call next('router') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, and then pass control to subsequent routes if there is no reason to proceed with the current route.

app.put('/', function(req, res) {
    res.send('PUT request to homepage');
});

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

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. This method is similar to res.render(), except it cannot send the rendered HTML to the client.

Think of app.render() as a utility function for generating rendered view strings. Internally, res.render() uses app.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 to true. In a production environment, view caching is enabled by default.

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

app.route(path)

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

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 the setting name to value. name is one of the properties from the Application settings table.

Calling app.set('foo', true) for a Boolean property is equivalent to calling app.enable('foo'). Similarly, calling app.set('foo', false) is equivalent to calling app.disable('foo').

You can get the value of a setting with app.get():

app.set('title', 'My Site');
app.get('title'); // 'My Site'

Application Settings

If name is one of the application settings, it will affect the behavior of the application. Below is a list of application settings.

Property Type Description Default
case sensitive routing Boolean Enable case sensitivity. Disabled. Treats /Foo and /foo as the same.
env String Environment mode. process.env.NODE_ENV (the NODE_ENV environment variable) or "development"
etag Varied Set the ETag response header. Possible values, see etag options table and HTTP ETag header weak
jsonp callback name String Specifies the default JSONP callback name. ?callback=
json replacer String JSON replacer callback null
json spaces Number When this value is set, it sends a prettified JSON string with indentation spaces. Disabled
query parser Varied Set to false to disable the query parser, or set to simple, extended, or implement your own query string parsing function. simple is based on Node's native query parsing, using querystring "extend"
strict routing Boolean Enable strict routing. Not enabled. Routes for /foo and /foo/ are treated the same.
subdomain offset Number The number of dot-separated parts of the host to remove to access subdomain 2
trust proxy Varied Indicates that the app is behind a reverse proxy, using x-Forwarded-* headers to determine the connection and client's IP address. Note: X-Forwarded-* headers can be spoofed, so detecting the client's IP address is unreliable. trust proxy is disabled by default. When enabled, Express attempts to determine the client's IP address from the front-facing proxy or a series of proxies. The req.ips property contains an array of IP addresses of the connected client. To enable it, set the trust proxy options as described in the trust proxy options table. The trust proxy implementation uses the proxy-addr package. For more information, refer to its documentation. Disable
views String or Array Directory or array of directories for the views. If an array, views are looked up in the order they appear in the array. process.cwd() + '/views'
view cache Boolean Enable view template compilation caching. Enabled by default in production.
view engine String When omitted, the default engine extension is used.
x-powered-by Boolean Enable the X-Powered-By: Express HTTP header. true

** Refer to Express behind proxies for more information.

Type Value
Boolean If true, the client's IP address is taken as the leftmost entry in the X-Forwarded-* headers. If false, the app is understood to be directly connected to the internet, and the client's IP address is derived from req.connection.remoteAddress. false is the default setting.
IP addresses An IP address, subnet, or an array of IP addresses and delegated subnets. A list of pre-configured subnet names is provided below. loopback - 127.0.0.1/8, ::1/128<br>linklocal - 169.254.0.0/16, fe80::/10<br>uniquelocal - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7 Use any of the following methods to set IP addresses: app.set('trust proxy', 'loopback') // specify a single subnet<br>app.set('trust proxy', 'loopback, 123.123.123.123') // specify a subnet and an address<br>app.set('trust proxy', 'loopback, linklocal, uniquelocal') // specify multiple subnets as CSV<br>app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']) // specify multiple subnets as an array When specified, the IP address or subnet is excluded, and the closest untrusted address to the application server is considered the client's IP address.
Number Trust connections to the app through a reverse proxy within n hops of the client.
Function Custom trust proxy delegation mechanism. Use this if you know what you are doing. app.set('trust proxy', function (ip) {<br> if (ip === '127.0.0.1' ip === '123.123.123.123') return true; // trusted IPs<br> else return false;<br> })

* *ETag functionality is implemented using the etag package. For more information, refer to its documentation.

Type Value
Boolean Set to true to enable weak ETag. This is the default setting. Set to false to disable all ETags.
String If "strong", enable strong ETag. If "weak", enable weak ETag.
Function Custom ETag method implementation. Use this if you know what you are doing. app.set('etag', function (body, encoding) {<br> return generateHash(body, encoding); // consider the function is defined<br> })

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

Mounts the middleware method(s) to the path. If path is not specified, it defaults to "/".

>

A route will match any path that follows its path immediately with a "/". For example, app.use('/apple', ...) will match "/apple", "/apple/images", "/apple/images/news", etc.

req.originalUrl in a middleware is a combination of req.baseUrl and req.path, 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 middleware is mounted on a path, it executes whenever the request's path prefix matches the route's path. Since the default path is /, middleware mounted without a path executes for every request to the app.

// 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 functions are processed in the order they are included in the code, so the order of middleware inclusion is 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 to match paths, or an array of combinations of these.

Here are simple examples of paths.

Type Example
Path // will match paths starting with /abcd<br>app.use('/abcd', function (req, res, next) {<br> next();<br>})
Path Pattern // will match paths starting with /abcd and /abd<br>app.use('/abc?d', function (req, res, next) {<br> next();<br>})<br>// will match paths starting with /abcd, /abbcd, /abbbbbcd and so on<br>app.use('/ab+cd', function (req, res, next) {<br> next();<br>})<br>// will match paths starting with /abcd, /abxcd, /abFOOcd, /abbArcd and so on<br>app.use('/ab*cd', function (req, res, next) {<br> next();<br>})<br>// will match paths starting with /ad and /abcd<br>app.use('/a(bc)?d', function (req, res, next) {<br> next();<br>})
Regular Expression // will match paths starting with /abc and /xyz<br>app.use(/\/abc \/xyz/, function (req, res, next) {<br> next();<br>})
Array // will match paths starting with /abcd, /xyza, /lmn, and /pqr<br>app.use(['/abcd', '/xyza', /\/lmn \/pqr/], function (req, res, next) {<br> next();<br>})

The method can be a middleware function, a series of middleware functions, an array of middleware functions, or combinations thereof. Since router and app implement the middleware interface, you can use them as you would any other middleware function.

| Usage | Example | | --- | --- | Single Middleware: You can locally define and mount a middleware.

app.use(function (req, res, next) {
  next();
});

A router is a valid middleware.

var router = express.Router();
router.get('/', function (req, res, next) {
  next();
});
app.use(router);

An Express application is a valid middleware.

var subApp = express();
subApp.get('/', function (req, res, next) {
  next();
});
app.use(subApp);

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: Organize a group of middleware logically using an array. 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 the above 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);

Here are some examples of using the express.static middleware in an Express application.

To host static resources located in the public directory under the application directory:

// GET /style.css etc
app.use(express.static(__dirname + '/public'));

To mount middleware to serve static resources at the /static path, only when the request is prefixed with /static:

// GET /static/style.css etc.
app.use('/static', express.static(__dirname + '/public'));

To disable logging for static resource requests by loading the logger middleware after the static middleware:

app.use(express.static(__dirname + '/public'));
app.use(logger());

To host static resources from different paths, with the ./public path being more likely to match first:

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));

Request

The req object represents an HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation, according to convention, the object is always referred to as req (and the HTTP response is res), but its actual name is determined by the parameters to the callback function in which you're working.

For example:

app.get('/user/:id', function(req, res) {
    res.send('user' + req.params.id);
});

You can also name the objects as you like:

app.get('/user/:id', function(request, response) {
    response.send('user' + request.params.id);
});

Properties

In Express 4, req.files is no longer available on the req object by default. To access uploaded files via the req.files object, you can use a multipart-handling middleware like busboy, multer, formidable, multipraty, connect-multiparty, or pez.

req.app

This property holds a reference to the instance of the Express application that is using the middleware.

If you follow the pattern in which you create a module that exports a middleware which is only available to that module, you can access the Express instance using req.app.

For example:

// 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 was 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 load the router on a path pattern or a series of path patterns, the baseUrl property returns the matched string, not the pattern(s). In the following example, the greet router is loaded on two path patterns.

app.use(['/gre+t', 'hel{2}o'], greet); // load the greet router on '/gre+t' and '/hel{2}o'

When a request path is /greet/jp, req.baseUrl is /greet. When a request path is /hello/jp, req.baseUrl is /hello. req.baseUrl is similar to the mountpath property of the app object, except app.mountpath returns the matched path patterns.

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer.

The following example shows how to use body-parser middleware to populate req.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 that contains cookies sent by the request. If the request contains no cookies, it defaults to {}.

// Cookie: name=tj
req.cookies.name
// => "tj"

For more information, issues, or concerns, see cookie-parser.

req.fresh

Indicates whether the request is "fresh." It is the opposite of req.stale.

It is true if the cache-control request header does not have a no-cache directive and any of the following are true:

req.hostname

Contains the hostname derived from the Host HTTP header.

When the trust proxy setting is enabled, the X-Forwarded-Host header is used instead of the Host. This header can be set by the client or by the proxy.

// Host: "example.com"
req.hostname
// => "example.com"

req.ips

When the trust proxy setting is enabled, this property contains an array of IP addresses specified in the X-Forwarded-For request header. Otherwise, it contains an empty array. This property is useful for identifying the originating IP addresses of a client connecting through a proxy or load balancer.

// X-Forwarded-For: client, proxy1, proxy2
req.ips
// => ["client", "proxy1", "proxy2"]

req.method

Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on.

req.originalUrl

req.url is not a native Express property, it is inherited from Node's http module.

This property is much like req.url, but it retains the original request URL, allowing you to rewrite req.url freely for internal routing purposes. For example, the "mounting" feature of app.use() will rewrite req.url to strip the mount point.

// GET /search?q=something
req.originalUrl
// => "/search?q=something"

req.params

This property is an object containing properties mapped to the named route "parameters". For example, if you have the route /user/:name, then the "name" property is available as req.params.name. This object defaults to {}.

// GET /user/tj
req.params.name
// => "tj"

req.path

Contains the path part of the request URL.

// example.com/users?sort=desc
req.path
// => "/users"

req.protocol

Contains the request protocol string: either http or https when requested with TLS. When the trust proxy setting is enabled, the X-Forwarded-Proto header field will be trusted and used if present.

req.protocol
// => "http"

req.query

This property is an object containing a property for each query string parameter in the route. If there is no query string, it is the 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

Contains the currently-matched route, a string. For example:

app.get('/user/:id?', function userIdHandler(req, res) {
    console.log(req.route);
    res.send('GET');
});

Example output from the previous snippet:

{ path: '/user/:id?',
  stack:
   [ { handle: [Function: userIdHandler],
       name: 'userIdHandler',
       params: undefined,
       path: undefined,
       keys: [],
       regexp: /^\/user(?:\/([^\/]+?))?\/?$/i,
       method: 'get' } ],
  methods: { get: true } }

req.secure

A Boolean that is true if a TLS connection is established. Equivalent to:

'https' == req.protocol;

req.signedCookies

When using cookie-parser middleware, this property contains signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show developer intent; otherwise, a malicious attack could be placed on req.cookie values (which are easy to spoof). Note that signing a cookie does not make it "hidden” or encrypted; but simply prevents tampering (because the secret used to sign is private).

If no signed cookies are sent, the property defaults to {}.

// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3
req.signedCookies.user
// => "tobi"

req.stale

Indicates whether the request is "stale," which is the opposite of req.fresh.

req.stale
// => true

req.subdomains

An array of subdomains in the domain name of the request.

// Host: "tobi.ferrets.example.com"
req.subdomains
// => ["ferrets", "tobi"]

req.xhr

A Boolean value that is true if the request’s X-Requested-With header field is "XMLHttpRequest", indicating that the request was issued by a client library such as jQuery.

req.xhr
// => true

Methods

req.accepts(types)

Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. The method returns the best match, or if none of the specified content types is acceptable, returns false (in which case, the application should respond with 406 "Not Acceptable").

The type value may be a single MIME type string (such as "application/json"), an extension name such as "json", a comma-delimited list, or an array. For lists or arrays, the method returns the best match (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');
// => false

// Accept: text/*;q=.5, application/json
req.accepts(['html', 'json']);
// => "json"

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

Returns the first accepted charset of the specified character sets, based on the request’s Accept-Charset HTTP header field. If none of the specified charsets is accepted, returns false.

req.acceptsCharsets('utf-8', 'iso-8859-1');
// => "utf-8"

req.acceptsCharsets(['utf-8', 'iso-8859-1']);
// => "utf-8"

req.acceptsCharsets('utf-7');
// => false

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

Returns the first accepted encoding of the specified encodings, based on the request’s Accept-Encoding HTTP header field. If none of the specified encodings is accepted, returns false.

req.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"

req.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"

req.acceptsEncodings('br');
// => false

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

Returns the first accepted language of the specified languages, based on the request’s Accept-Language HTTP header field. If none of the specified languages is accepted, returns false.

req.acceptsLanguages('en-US', 'en-GB', 'en');
// => "en-US"

req.acceptsLanguages(['en-US', 'en-GB', 'en']);
// => "en-US"

req.acceptsLanguages('fr');
// => false

req.get(field)

Returns the specified HTTP request header field (case-insensitive match). The Referrer and Referer fields are interchangeable.

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

req.get('content-type');
// => "text/plain"

req.get('Something');
// => undefined

It is also aliased as req.header(field).

req.is(type)

Returns the matching content type if the incoming request’s "Content-Type" HTTP header field matches the MIME type specified by the type parameter. If the request has no body, returns null. Returns false if there is no match.

// 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');
// =>
When the **trust proxy** setting is enabled, this property contains an array of IP addresses specified in the **X-Forwarded-For** request header. Otherwise, it contains an empty array. This header can be set by the client or by the proxy.

For example, if **X-Forwarded-For** is **client**, **proxy1**, **proxy2**, **req.ips** would be **["client", "proxy1", "proxy2"]**, where **proxy2** is the farthest downstream.

#### req.originalUrl

**req.url** is not a native **Express** property; it inherits from [Node's http module](https://nodejs.org/api/http.html#http_message_url).

This property is similar to **req.url**; however, it retains the original request URL, allowing you to rewrite **req.url** freely for internal routing purposes. For example, the **mounting** feature of **app.use()** can rewrite **req.url** to strip the mount point.

// GET /search?q=something req.originalUrl // => "/search?q=something"


#### req.params

An object containing properties mapped to the named route parameters. For example, if you have a route **/user/:name**, the **name** property is available as **req.params.name**. This object defaults to **{}**.

// GET /user/tj req.params.name // => "tj"


When using regular expressions to define route rules, captured groups are typically accessed using **req.params[n]**, where **n** is the nth captured group. This rule applies to unnamed wildcard matches, such as the route **/file/***.

// 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 within a middleware, the mount point is not included in **req.path**. You can refer to [app.use()](express-4-x-api.html#toc_25) for more information.

#### req.protocol

The request protocol, typically **http**, or **https** when TLS encryption is enabled.

When the **trust proxy** setting is enabled, if the **X-Forwarded-Proto** header is present, it will be trusted and used. This header can be set by the client or by the proxy.

req.protocol // => "http"


#### req.query

An object containing a property for each query string parameter in the route. If there is no query 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, represented as a string. For example:

app.get('/user/:id?', function userIdHandler(req, res) { console.log(req.route); res.send('GET') })


The output of the above snippet would be:

{ 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 that is true if a TLS connection is established. Equivalent to:

'https' == req.protocol;


#### req.signedCookies

When using the **cookie-parser** middleware, this property contains the signed cookies sent by the request, unsigned and ready for use. Signed cookies reside in a different object to show the developer's intention; otherwise, a malicious attack could be placed on **req.cookie** values (which are easy to spoof). Note that signing a cookie does not hide or encrypt its value; it only prevents tampering (because the secret used for signing is private). If no signed cookies are sent, the property defaults to **{}**.

// Cookie: user=tobi.CP7AWaXDfAKIRfH49dQzKJx7sKzzSoPq7/AcBBRVwlI3 req.signedCookies.user // => "tobi"


For more information, issues, or concerns, see [cookie-parser](https://github.com/expressjs/cookie-parser).

#### req.stale

Indicates whether the request is "stale," which is the opposite of **req.fresh**. For more information, see [req.fresh](express-4-x-api.html#toc_31).

req.stale // => true


#### req.subdomains

An array of subdomains in the domain name of the request.

// Host: "tobi.ferrets.example.com" req.subdomains // => ["ferrets", "tobi"]


#### req.xhr

A Boolean value that is true if the request’s **X-Requested-With** header field is "XMLHttpRequest", indicating that the request was issued by a client library such as jQuery.

req.xhr // => true


### Methods

#### req.accepts(types)

Checks if the specified content types are acceptable, based on the request’s Accept HTTP header field. This method returns the best match, or if none match, returns undefined (in which case, the application should respond with 406 "Not Acceptable").

The type value may be a single MIME type string (such as "application/json"), an extension name such as "json", a comma-delimited list, or an array. For lists or arrays, this method returns the best match (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, see [accepts](https://github.com/expressjs/accepts).

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

Returns the first accepted charset of the specified character sets, based on the request’s **Accept-Charset** HTTP header field. If none of the specified charsets are accepted, it returns false.

For more information, or if you have questions or concerns, see [accepts](https://github.com/expressjs/accepts).

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

Returns the first accepted encoding of the specified encodings, based on the request’s **Accept-Encoding** HTTP header field. If none of the specified encodings are accepted, it returns false.

For more information, or if you have questions or concerns, see [accepts](https://github.com/expressjs/accepts).

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

Returns the first accepted language of the specified languages, based on the request’s **Accept-Language** HTTP header field. If none of the specified languages are accepted, it returns false.

For more information, or if you have questions or concerns, see [accepts](https://github.com/expressjs/accepts).

#### req.get(field)

Returns the specified HTTP request header field (case-insensitive match). The **Referrer** and **Referer** fields are interchangeable.

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


It is a alias for req.header(field).

#### req.is(type)

Returns true if the incoming request’s **Content-Type** HTTP header field matches the MIME type specified by the type parameter. Otherwise, it returns false.

// 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, see [type-is](https://github.com/expressjs/type-is).

#### req.param(name [, defaultValue])

Deprecated. Can use **req.params**, **req.body**, or **req.query** instead, as appropriate.
Returns the value of the current parameter **name**.

// ?name=tobi req.param('name') // => "tobi" // POST name=tobi req.param('name') // => "tobi" // /user/tobi for /user/:name req.param('name') // => "tobi"


Searches in the following order:

- req.params
- req.body
- req.query

Optionally, you can specify a **defaultValue** to set a default value if the parameter is not found in any of the request objects.

It is clearer to retrieve directly via **req.params**, **req.body**, and **req.query** unless you are certain about the input from each object. The **body-parser** middleware must be loaded if you use **req.param()**. See [req.body](express-4-x-api.html#toc_30) for details.

## Response

The **res** object represents the HTTP response that an Express app sends when it gets an HTTP request. In this documentation, the object is always referred to as **res** (and the HTTP request is **req**), but its actual name is determined by the parameters to the callback function in which you're working.

For example:

app.get('/user/:id', function(req, res) { res.send('user' + req.params.id); });


This is equivalent to:

app.get('/user/:id', function(request, response) { response.send('user' + request.params.id); });


### Properties

#### res.app

This property holds a reference to the instance of the Express application that is using the middleware.

res.app is identical to the req.app property in the request object.

#### res.headersSent

Boolean property that indicates if the app sent HTTP headers for the response.

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


#### res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

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


### Methods

#### res.append(field [, value])

The res.append() method is supported in Express v4.11.0+

Appends the specified **value** to the HTTP response header **field**. If the header is not already set, it creates the header with the specified value. The **value** can be a string or an array.

Note: Calling res.set() after res.append() will reset the previously-set header value.

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])

Sets the HTTP response Content-Disposition header field to "attachment". If a **filename** is given, it sets the Content-Type based on the extension name via res.type(), and sets the Content-Disposition "filename=" parameter.

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])

Sets a cookie **name** to **value**. The **value** parameter may be a string or object converted to JSON.

The **options** parameter is an object that can have the following properties.

| Property | Type | Description |
| --- | --- | --- |
| domain | String | Domain name for the cookie. Defaults to the domain name of the app. |
| expires | Date | Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. |
| httpOnly | Boolean | Flags the cookie to be accessible only by the web server. |
| maxAge | String | Convenient option for setting the expiry time relative to the current time in milliseconds. |
| path | String | Path for the cookie. Defaults to /. |
| secure | Boolean | Marks the cookie to be used with HTTPS only. |
| signed | Boolean | Indicates if the cookie should be signed. |

res.cookie() essentially sets the Set-Cookie header based on the options provided. If no options are specified, the default values specified in RFC6265 are used.

Examples:

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


The maxAge option is a convenience option for setting the expiry time relative to the current time in milliseconds. The following example is equivalent to the second example above:

res.cookie('rememberme', '1', {'maxAge':90000}, "httpOnly":true);


You can pass an object as the value parameter, which will be serialized into a JSON string and parsed by the bodyParser() middleware.

res.cookie('cart', {'items':[1, 2, 3]}); res.cookie('cart', {'items':[1, 2, 3]}, {'maxAge':90000});


When using the cookie-parser middleware, this method also supports signed cookies. Simply set the signed option to true in the options object. Then res.cookie() will use the secret passed to cookieParser(secret) to sign the value.

res.cookie('name', 'tobi', {'signed':true});


#### res.clearCookie(name [, options])

Clears the cookie specified by **name**. For details about the **options** object, see res.cookie().

res.cookie('name', 'tobi', {'path':'/admin'}); res.clearCookie('name', {'path':'admin'});


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

Transfers the file at **path** as an "attachment". Typically, browsers will prompt the user for download. By default, the Content-Disposition header "filename=" parameter is the file path (this typically appears in the browser dialog). Override this default with the **filename** parameter.

When an error occurs or the transfer is complete, the method will call the callback specified by **fn**. This method uses res.sendFile() to transfer the file.

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])

Ends the response process. This method actually comes from Node core, specifically [response.end() method of http.ServerResponse](https://nodejs.org/api/http.html#http_response_end_data_encoding_callback).

Use to quickly end the response without any data. If you need to respond with data, use methods such as res.send() and res.json().

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


#### res.format(object)

Performs content-negotiation on the Accept HTTP header on the request object. It uses req.accepts() to select a handler for the request based on the acceptable types ordered by their quality values. If the header is not specified, the first callback is invoked. When no match is found, the server responds with 406 "Not Acceptable", or calls the **default** callback.

The Content-Type is set accordingly when a callback is selected. However, you can modify that within the callback using methods such as res.set() or res.type().

The following example would respond with `{"message":"hey"}` when the Accept header field is set to "application/json" or "*/json" (however, if it is "/*", then the response will be "hey").

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'); } });


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'); } });


In addition to canonicalized MIME types, you can also use file extensions to map these types to avoid verbose implementations:

res.format({ text: function() { res.send('hey'); }, html: function() { res.send('<p>hey</p>'); }, json: function() { res.send({ message: 'hey' }); } });


#### res.get(field)

Returns the HTTP response header specified by **field**. The match is case-insensitive.

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


#### res.json([body])

Sends a JSON response. This method is identical to `res.send()` with an object or array as the parameter. However, you can use it to convert other values to JSON, such as `null` and `undefined` (although these are technically not valid JSON).

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


#### res.jsonp([body])

Sends a JSON response with JSONP support. This method is identical to `res.json()`, except that it opts-in to JSONP callback support.

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


By default, the JSONP callback name is simply `callback`. Override this with the [jsonp callback name](express-4-x-api.html#app.settings.table) setting.

Here are some examples using JSONP responses with the same code:

// ?callback=foo res.jsonp({ user: 'tobi' }) // => foo({"user": "tobi"}) app.set('jsonp callback name', 'cb') // ?cb=foo res.status(500).jsonp({ error: 'message' }) // => foo({"error": "message"})


#### res.links(links)

Joins the **links** provided as properties of the parameter, then sets them to the Link HTTP header of the response.

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


The result is:

Link: http://api.example.com/users?page=2; rel="next", http://api.example.com/users?page=5; rel="last"


#### res.location(path)

Sets the response **Location** HTTP header to the specified **path** parameter.

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


When the **path** parameter is `back`, it has a special meaning, which specifies the URL as the value of the `Referer` header of the request. If the request does not specify the `Referer` header, it is set to `/`.

>

Express passes the specified URL string as the value in the response's **Location** header without any testing or manipulation, except for the `back` parameter. The browser redirects the user to the **location** URL or the **Referer** URL (in the case of the `back` parameter).

#### res.redirect([status,] path)

Redirects to the URL derived from the specified **path**, with specified [HTTP status code](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html) **status**. If you don't specify **status**, the status code defaults to "302 Found".

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


Redirects can also be a full URL to redirect to a different site.

res.redirect('http://google.com');


Redirects can be relative to the root of the host name. For example, if the application is at `http://example.com/admin/post/new`, the following would redirect to `http://example.com/admin`:

res.redirect('/admin');


Redirects can be relative to the current URL. For example, from `http://example.com/blog/admin/` (note the trailing `/`), the following would redirect to `http://example.com/blog/admin/post/new`.

res.redirect('post/new');


If you found the above a bit confusing, think of path segments as directories (with trailing slashes) and files, it will start to make sense.

Relative path redirects are also possible. If you were on `http://example.com/admin/post/new`, the following would redirect to `http://example.com/admin/post`:

res.redirect('..');


The `back` parameter redirects to the [referer](http://en.wikipedia.org/wiki/HTTP_referer) URL, defaulting to `/` when there is no referer.

res.redirect('back');


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

Renders a view and sends the rendered HTML string to the client. Optional parameters:

- **locals**, an object whose properties define local variables for the view.
- **callback**, a callback function. If provided, the method returns both the possible error and rendered string, but does not perform an automated response. When an error occurs, the method calls `next(err)` internally.

>

The local variable cache enables view caching. Set it to true in production to cache views during development; view caching is enabled by default in production.

// 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])

Sends an HTTP response.

The **body** parameter can be a `Buffer` object, 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' });


This method performs a myriad of useful tasks for simple non-streaming responses: For example, it automatically assigns the `Content-Length` HTTP response header field (unless previously defined) and provides automatic HEAD and HTTP cache freshness support.

When the parameter is a `Buffer` object, the method sets the `Content-Type` response header field to `application/octet-stream`, unless previously defined as shown below:

res.set('Content-Type', 'text/html'); res.send(new Buffer('<p>some html</p>'));


When the parameter is a string, the method sets the `Content-Type` to `text/html`:

res.send('<p>some html</p>');


When the parameter is an object or array, Express responds with the JSON representation:

res.send({ user: 'tobi' }); res.send([1, 2, 3]);


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

>

**res.sendFile()** is supported from **Express v4.8.0** onwards.

Transfers the file at the given **path**. Sets the `Content-Type` response HTTP header field based on the filename's extension. Unless the `root` option is set in the `options` object, **path** must be an absolute path to the file.

The following table provides details on the `options` parameter:

| Property | Description | Default | Availability |
| --- | --- | --- | --- |
| maxAge | Sets the max-age property of the Cache-Control header in milliseconds or a string in [ms format](https://www.npmjs.org/package/ms) | 0 |  |
| root | Root directory for relative filenames |  |  |
| lastModified | Sets the Last-Modified header to the last modified date of the file on the OS. Set to false to disable it | Enabled | 4.9.0+ |
| headers | An object containing HTTP headers to serve with the file |  |  |
| dotfiles | Option for serving dotfiles. Possible values are "allow", "deny", "ignore" | "ignore" |  |

res.sendFile('/path/to/file');

When the transmission is complete or an error occurs, this method calls the **fn** callback method. If the 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.

Below is an example using **res.sendFile()** with all parameters:

```javascript
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 shown 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 cannot see that.');
        }
    });
});

For more information, or if you have questions or concerns, you can refer to send.

res.sendStatus(statusCode)

Sets the response object's HTTP status code to statusCode and sends the string representation of statusCode 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 to statusCode and the string representation of the code is used as the body.

res.sendStatus(2000); // equivalent to res.status(2000).send('2000');

More about HTTP Status Codes

res.set(field [, value])

Sets the response object's HTTP header field to value. 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'
});

This is equivalent to res.header(field [, value]).

res.status(code)

This method is used to set the HTTP status of the response object. It is a chainable alias of Node's response.statusCode.

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

res.type(type)

This method sets the Content-Type HTTP header of the response based on the MIME type specified in type. If type contains a '/' character, it will directly set the Content-Type to type.

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 if it is not already present.

The purpose of the Vary header is to inform caching servers how to determine if a request is the same. It acts as a key for caching, so if the Vary header includes 'User-Agent', the cache server will consider the same request from different user agents as different requests.

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

Router

A router object is an isolated instance of middleware and routes. You can think of it as a "mini-application" capable of only middleware and routing functions. Each Express application has a built-in app router.

Routes themselves act as middleware, so you can use them as an argument to app.use() or as an argument to another router's use() method.

The top-level express object has a Router() method that you can use to create a new router object.

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

Router([options])

You can create a router as follows:

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

The options parameter can specify the behavior of the router and has the following options:

Property Description Default Availability
caseSensitive Enables case sensitivity. Disabled by default. Treats /Foo and /foo as the same.
mergeParams Preserves the req.params values from the parent router. If the parent and child have conflicting param names, the child's params take precedence. false 4.5.0+
strict Enables strict routing. Disabled by default, /foo and /foo/ are treated the same.

You can treat the router as a mini-application, adding middleware and HTTP route methods (such as get, put, post, etc.) to it.

// 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 on a specific root URL, allowing you to organize your routes into different files or even mini-applications.

// Only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);

Methods

router.all(path, [callback, ...] callback)

This method is like the router.METHOD() methods, except that it matches all HTTP verbs.

This method is useful for mapping global logic to specific path prefixes or any route. For example, if you place the following route at the top of all other route definitions, it will require that all routes from this point require authentication and automatically load a user. Remember, these global functions do not have to end the request-response cycle: loaduser can perform a task, then call next() to continue to the next route.

router.all('*', requireAuthentication, loadUser);

Equivalent to:

router.all('*', requireAuthentication)
router.all('*', loadUser);

Here is an example of a whitelist for global functions. 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)

The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, etc., in lowercase. Thus, the actual methods are router.get(), router.put(), router.post(), etc.

// 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 on a specific root URL, allowing you to organize your routes into different files or even mini-applications.

// Only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);

You can provide multiple callback functions that behave like middleware, except that these callbacks can invoke next('router') to bypass the remaining route callbacks. You can use this mechanism to impose preconditions on a route, and if the request does not meet the preconditions, you can pass control to subsequent routes.

The following snippet illustrates the most simple route definition. Express converts the path strings to regular expressions, used internally to match incoming requests. When matching, query strings are not considered, so both "GET /" and "GET /?name=tobi" will match the route below.

router.get('/', function(req, res) {
    res.send('Hello World');
});

If you have special restrictions on the path you can use regular expressions, for example, the following will 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, where name is the parameter name, and function is the callback method. The parameters of the callback function are the request object, the response object, the next middleware, the parameter value, and the parameter name, in that order. Although name is technically optional, documentation from Express V4.11.0 onwards does not recommend omitting it.

Unlike app.param(), router.param() does not accept an array of routes as a parameter.

For example, when :user appears in the route path, you can map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

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'));
        }
    });
});

For routes defined with param callbacks, they are local. They are not inherited by mounted apps or routers. Therefore, param callbacks defined on router will only be triggered by route parameters defined on router routes.

On routes with param definitions, the param callbacks are invoked first, and they are invoked only once in a request-response cycle, even if multiple routes match, as shown in the example below:

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 matches too');
    res.end();
});

When GET /user/42, the result is:

CALLED ONLY ONCE
although this matches
and this matches too

The router.param(callback) described in the following section was deprecated after v4.11.0.

By passing only a callback parameter to router.param(name, callback), the behavior of router.param(name, callback) is completely changed. This callback parameter is a custom method that defines how router.param(name, callback) should behave. This method must take two parameters and return a middleware.

The first parameter of this callback is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object that might be used in the implementation of the returned middleware.

The middleware returned by this callback determines the behavior when the URL contains the captured parameter.

In the following example, the router.param(name, callback) signature is modified to router.param(name, accessId). Instead of accepting a parameter name and a callback, router.param() 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) signature remains the same, but it is replaced with a middleware that defines a custom data type checking method to validate the user id.

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 an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Using router.route() helps to avoid duplicate route naming (and thus typo errors).

Building on the router.param() example above, the following code shows how to use router.route() to specify various HTTP method handlers.

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 approach reuses the single /users/:userid path and adds handlers for various HTTP methods.

router.use([path], [function, ...] function)

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches the path.

This method is similar to app.use(). A simple example and use case is described below. See app.use() for more information.

Middleware is like a plumbing pipe, requests start at the first middleware you define and move to the next middleware in the stack 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 from the mount point
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 mount path is stripped and inaccessible. The main impact of this feature is that mounting the same middleware for different paths may not alter the code even if the prefix has changed.

The order in which you define middleware using router.use() is important. Middleware is invoked in sequence, so the order determines the priority. For example, logging is typically the first middleware you would use to ensure every request is logged.

var logger = require('morgan');
router.use(logger());
router.use(express.static(__dirname + '/public'));
router.use(function(req, res) {
    res.send('Hello');
});

Now, to support not logging static file requests but continuing to log routes and middleware defined after logger(), you can simply move static() to the front:

router.use(express.static(__dirname + '/public'));
router.use(logger());
router.use(function(req, res){
  res.send('Hello');
});

Another clear example is hosting static files from different paths. You can place ./public at the front to give it higher priority:

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/files'));
app.use(express.static(__dirname + '/uploads'));

The router.use() method also supports named parameters, so your mount points can preload named parameters for other routes, which is beneficial.

>

Original source: https://github.com/bajian/express_api_4.x_chinese

❮ 2021 Frontend Learnpath Android Tutorial Shader ❯