应用对象
app.set(name, value):用于设置Express配置中的环境变量
Assigns setting name to value, 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'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').
Retrieve the value of a setting with app.get().
指定要值的设置名称,其中名称是应用程序设置表中的属性之一。
调用应用程序设置('foo ',真的)一个布尔属性调用应用程序相同。使('foo”)。同样,调用应用程序设置('foo,false)为布尔属性调用应用程序相同。禁用('foo”)。
检索设置应用程序的价值。get()。
app.set('title', 'My Site');
app.get('title'); // "My Site"
app.get(name):用于获取Express配置中的环境变量
Returns the value of name 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.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 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.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
// => '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.(一旦设置,对app.locals属性值持续贯穿在生活中的应用,在res.locals性质,只为请求的寿命是有效的对比)
You can access 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.use([path,] function [, function...]):创建处理HTTP中间件
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).(返回一个单一的路线的一个实例,然后你就可以使用可选的中间件处理HTTP动词。使用的应用程序。route()避免重复路线名称(因此打印错误)。)
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.param([name], callback)
Add 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, and the value 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 each declared parameter except the last one, a call to next inside the callback will call the callback for the next declared parameter. For the last parameter, a call to next will call the next middleware in place for the route currently being processed, just like it would if name were just a string.
For example, when :user is present in a route path, you may 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) {
// try to get the user details from the User model and attach it to the request object
User.find(id, function(err, user) {
if (err) {
next(err);
} else if (user) {
req.user = user;
next();
} else {
next(new Error('failed to load user'));
}
});
});
Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on app will be triggered only 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 examples.
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();
});
On GET /user/42, the following is printed:
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) {
console.log('and this matches too');
res.end();
});
On GET /user/42/3, the following is printed:
CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too
The following section describes app.param(callback), which is deprecated as of v4.11.0.
The behavior of the app.param(name, callback) method can be altered entirely by passing only a function to app.param(). This function is a custom implementation of how app.param(name, callback) should behave - it accepts two parameters and must return a middleware.
The first parameter of this function is the name of the URL parameter that should be captured, the second parameter can be any JavaScript object which might be used for returning the middleware implementation.
The middleware returned by the function decides the behavior of what happens when a URL parameter is captured.
In this example, the app.param(name, callback) signature is modified to app.param(name, accessId). Instead of accepting a name and a callback, app.param() will now accept a name and a number.
var express = require('express');
var app = express();
// customizing the behavior of app.param()
app.param(function(param, option) {
return function (req, res, next, val) {
if (val == option) {
next();
}
else {
res.sendStatus(403);
}
}
});
// using the customized app.param()
app.param('id', 1337);
// route to trigger the capture
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) signature remains the same, but instead of a middleware callback, a custom data type checking function has been defined to validate the data type of the user id.
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);
});
The ‘.’ character can’t be used to capture a character in your capturing regexp. For example you can’t use '/user-.+/' to capture 'users-gami', use [\s\S] or [\w\W] instead (as in '/user-[\s\S]+/'.
Examples:
//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);
请求对象
req.query
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.param(name [, defaultValue])
Deprecated. Use either req.params, req.body or req.query, as applicable.
Return the value of param name when present.
// ?name=tobi
req.param('name')
// => "tobi"
// POST name=tobi
req.param('name')
// => "tobi"
// /user/tobi for /user/:name
req.param('name')
// => "tobi"
req.path
Contains the path part of the request URL.
// example.com/users?sort=desc
req.path
// => "/users"
req.hostname
Contains the hostname from the “Host” HTTP header.
// Host: "example.com:3000"
req.hostname
// => "example.com"
req.ip
The remote IP address of the request.
If the trust proxy is setting enabled, it is the upstream address; see Express behind proxies for more information.
req.ip
// => "127.0.0.1"
req.cookies
When using 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.
响应对象
res.status(code):设置响应的HTTP状态码
Use this method to set the HTTP status for the response. 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.set(field [, value]):设置响应HTTP报头
Sets the response’s HTTP header field to value. To set multiple fields at once, pass an object as the parameter.
res.set('Content-Type', 'text/plain');
res.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
res.cookie(name, value [, options])
res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
res.redirect([status,] path)
res.send([body])
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.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 invokes next(err) internally.
The local variable cache enables view caching. Set it to true, to cache the view during development; view caching is enabled in production by default.
// 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) {
// ...
});
外部中间件
Morgan 记录HTTP请求日志
body-parser 对请求body进行解析,支持多种HTTP请求类型
method-override 用于处理客户端不支持的HTTP方法,如PUT等
Compression 对响应数据使用gzip/deflate进行压缩
express.static
cookie-parser解析cookie,并将结果组装req.cookies对象
Session
MVC
水平文件夹结构
app文件夹用于保存Express应用的逻辑部分相关代码,安照MVC模式分为
controllers文件夹,控制器
index.server.controller.js
// Invoke 'strict' JavaScript mode
'use strict';
// Create a new 'render' controller method
exports.render = function(req, res) {
// If the session's 'lastVisit' property is set, print it out in the console
if (req.session.lastVisit) {
console.log(req.session.lastVisit);
}
// Set the session's 'lastVisit' property
req.session.lastVisit = new Date();
// Use the 'response' object to render the 'index' view with a 'title' property
res.render('index', {
title: 'Hello World'
});
};
models文件夹,模型
routes文件夹,路由中间件
index.server.routes.js
// Invoke 'strict' JavaScript mode
'use strict';
// Define the routes module' method
module.exports = function(app) {
// Load the 'index' controller
var index = require('../controllers/index.server.controller');
// Mount the 'index' controller's 'render' method
app.get('/', index.render);
};
views文件夹,视图
index.ejs
<!DOCTYPE html>
<html>
<head>
<!-- Use the 'title' property to render a page title -->
<title><%= title %></title>
</head>
<body>
<!-- Load the static image file -->
<img src="img/logo.png" alt="Logo">
<!-- Use the 'title' property to render a title element -->
<h1><%= title %></h1>
</body>
</html>
config文件夹用于存放Express应用的配置文件
env文件夹,存储Express应用环境配置
development.js
// Invoke 'strict' JavaScript mode
'use strict';
// Set the 'development' environment configuration object
module.exports = {
sessionSecret: 'developmentSessionSecret'
};
production.js
// Invoke 'strict' JavaScript mode
'use strict';
// Set the 'production' environment configuration object
module.exports = {
sessionSecret: 'productionSessionSecret'
};
test.js
// Invoke 'strict' JavaScript mode
'use strict';
// Set the 'test' environment configuration object
module.exports = {
sessionSecret: 'testSessionSecret'
};
config.js文件,用于Express应用配置
// Invoke 'strict' JavaScript mode
'use strict';
// Load the correct configuration file according to the 'NODE_ENV' variable
module.exports = require('./env/' + process.env.NODE_ENV + '.js');
express.js文件,用于Express应用初始化
// Invoke 'strict' JavaScript mode
'use strict';
// Load the module dependencies
var config = require('./config'),
express = require('express'),
morgan = require('morgan'),
compress = require('compression'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
session = require('express-session');
// Define the Express configuration method
module.exports = function() {
// Create a new Express application instance
var app = express();
// Use the 'NDOE_ENV' variable to activate the 'morgan' logger or 'compress' middleware
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
} else if (process.env.NODE_ENV === 'production') {
app.use(compress());
}
// Use the 'body-parser' and 'method-override' middleware functions
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// Configure the 'session' middleware
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret
}));
// Set the application view engine and 'views' folder
app.set('views', './app/views');
app.set('view engine', 'ejs');
// Load the 'index' routing file
require('../app/routes/index.server.routes.js')(app);
// Configure static file serving
app.use(express.static('./public'));
// Return the Express application instance
return app;
};
public文件夹用于保存浏览器端的静态文件,按MVC模式分为
config文件夹,用于存储AngularJS应用的配置文件
controllers文件夹,用于存储AngularJS应用的控制器文件
css文件夹,用于存放CSS
directives文件夹,用于存放AngularJS应用的指令文件
filters文件夹,用于存放AngulerJS应用的过滤器文件
img文件夹
views文件夹,存放AngularJS应用的视图文件
application.js文件,用于AngularJS应用的初始化
package.json存有用于管理应用依赖的元数据
{
"name": "MEAN",
"version": "0.0.3",
"dependencies": {
"express": "~4.8.8",
"morgan": "~1.3.0",
"compression": "~1.0.11",
"body-parser": "~1.8.0",
"method-override": "~2.2.0",
"express-session": "~1.7.6",
"ejs": "~1.0.0"
}
}
server.js是Node程序的主文件
// Invoke 'strict' JavaScript mode
'use strict';
// Set the 'NODE_ENV' variable
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// Load the 'express' module
var express = require('./config/express');
// Create a new Express application instance
var app = express();
// Use the Express application instance to listen to the '3000' port
app.listen(3000);
// Log the server status to the console
console.log('Server running at http://localhost:3000/');
// Use the module.exports property to expose our Express application instance for external usage
module.exports = app;
网友评论