express()
Creates an Express application. Theexpress()
function is a top-level function exported by the express module.var express = require('express');
var app = express();
Application
Theapp
object conventially denotes the Express application.
Create it by calling the top-level express()
function 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 a methods for- Routing HTTP requests; see for example, app.METHOD and app.param.
- Configuring middleware; see app.route.
- Rendering HTML views; see app.render.
- Registering a template engine; see app.engine.
Properties
app.locals
Theapp.locals
object is a JavaScript object, and its
properties are local variables within the application.app.locals.title
// => 'My App'
app.locals.email
// => 'me@myapp.com'
Once set, the value of app.locals
properties persist throughout the life of the application,
in contrast with res.locals properties that
are valid only for the lifetime of the request.You can accesss local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as app-level data. Note, however, that you cannot access local variables in middleware.
app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';
app.mountpath
Theapp.mountpath
property is the path pattern(s) on which a sub app was mounted.
A sub app is an instance of
express
which may be used for handling the request to a route.var express = required('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 baseUrl property of the req
object, except req.baseUrl
returns the matched URL path, instead of the matched pattern(s).If a sub-app is mounted on multiple path patterns,
app.mountpath
returns the list of patterns it is mounted on, 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))
Themount
event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed 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 ...])
This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.It’s useful for mapping “global” logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind 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 the equivalent:app.all('*', requireAuthentication)
app.all('*', loadUser);
Another example is white-listed “global” functionality.
The example is much like before, however it only restricts paths that start with
“/api”:app.all('/api/*', requireAuthentication);
app.delete(path, callback [, callback ...])
Routes HTTP DELETE requests 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 these callbacks can invoke
next('route')
to bypass the remaining route
callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control
to subsequent routes if there’s 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 settingname
to false
, where name
is one of the properties from the app settings table.
Calling app.set('foo', false)
for a Boolean property is the same as calling app.disable('foo')
.For example:
app.disable('trust proxy');
app.get('trust proxy');
// => false
app.disabled(name)
Returnstrue
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 settingname
to true
, where name
is one of the properties from the app settings table.
Calling app.set('foo', true)
for a Boolean property is the same as calling app.enable('foo')
.app.enable('trust proxy');
app.get('trust proxy');
// => true
app.enabled(name)
Returnstrue
if the 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 enginecallback
as ext
.By default, Express will
require()
the engine based on the file extension.
For example, if you try 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 this method for engines that do not provide .__express
out of the box,
or if you wish to “map” a different extension to the template engine.For example, to map the EJS template engine to “.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 seemlessly with Express.
var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
app.get(name)
Returns the value ofname
app setting, where name
is one of 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 HTTP GET requests 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 these callbacks can invoke
next('route')
to bypass the remaining route callback(s).
You can use this mechanism to impose pre-conditions on a route, then pass control to
subsequent routes if there’s 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 in fact 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 code base, 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');
var app = express();
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 areapp.get()
,
app.post()
, app.put()
, and so on. See below for the complete list.For more information, see the routing guide.
Express supports the following routing methods corresponding to the HTTP methods of the same names:
|
|
|
No comments:
Post a Comment