express应用内容(完)

469 阅读4分钟
  • app.engine(ext, callback)

给定的模板引擎注册callback为ext。

默认情况下,Express会根据文件扩展名来动态使用解析引擎(此引擎可以视为一个函数)。例如,如果您尝试呈现“foo.pug”文件,则Express会在内部调用以下步骤

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

对于不提供.__express开箱即用的引擎,或者如果想将扩展名使用不同名的模板引擎(例如html用ejs的引擎),需要使用这个设置。

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

在这种情况下,EJS提供了一个具有Express期望的相同签名(path, options, callback)的.renderFile()方法,但请注意,它在ejs.__express内部将此方法进行了别名,因此如果使用“.ejs”扩展名,则不需要执行任何操作。

app.set('views', path.join(__dirname, 'views')); // 设置views的目录,模板文件在的地方
app.engine('html', require('ejs').__express); // 使用ejs的render渲染html,指定html后缀使用的处理函数
app.set('view engine', 'html'); // 配置默认的拓展名,不写拓展名也可以,自动补充。
  • app.listen(path, callback)

  • app.listen(port, hostname, backlog, callback)

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

express()返回app的实际上是一个函数,旨在处理请求。可以轻松地使用相同的代码序提供HTTP和HTTPS版本:

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

app挂载端口的方法实际上是这样的:

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

name是参数名或这些名称的数组,callback是回调函数。这个玩意其实就是个监听器,等待着被触发器触发。

回调函数的参数依次为请求对象,响应对象,下一个中间件,参数值value和参数名key。

如果name是数组,callback则为每个参数名按顺序注册监听器。

此外,除了最后参数外,next在本次回调函数内将调用下一个参数的回调函数。对于最后一个参数,调用next将调用下一个中间件。

例如,当:user存在于路径路径中时,您可以映射用户加载逻辑以自动提供req.user给路径,或对参数输入执行验证。

GET https://user/lrh

app.param('user', function(req, res, next, id) {
// id == 'lrh'
  User.find(id, function(err, user) {
    if (err) {
      next(err);
    } else if (user) {
      req.user = user; //如果找到了对应的信息,放至req.user中传递向下,在本次的请求中将一直保存。
      next();
    } else {
      next(new Error('failed to load user'));
    }
  });
});

app.get('/user/:user', function (req, res, next) {
  console.log('这里会被匹配到');
  next();
});

它们将在请求 - 响应循环中仅被调用一次,即使参数在多个路由中匹配

app.param('id', function (req, res, next, id) {
  console.log('CALLED ONLY ONCE');
  next();
});

app.get('/user/:id', function (req, res, next) { // 路由1
  console.log('although this matches');
  next();
});

app.get('/user/:id', function (req, res) { // 路由2
  console.log('and this matches too');
  res.end();
});

//打印如下
CALLED ONLY ONCE
although this matches
and this matches too

我们在看一个关于数组参数的实例

app.param(['id', 'page'], function (req, res, next, value) { // 先触发id,再触发page,page触发后,next移动到第一个get
  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();
});

// 打印如下
CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too
  • app.path() 返回路径

var app = express()
 , blog = express()
 , blogAdmin = express();

app.use('/blog', blog);
blog.use('/admin', blogAdmin);

console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
  • app.render(view, locals, callback)

通过callback函数返回HTML文件。它接受一个可选参数,该参数是包含视图的局部变量的对象。它就像res.render()一样,除了它不能将渲染视图自己发送到客户端。(两者差别建议百度,就不做解释了)

将其app.render()视为用于生成呈现视图字符串的实用程序函数。内部res.render()用于app.render()渲染视图。

本地变量cache保留用于启用视图缓存。如果您想在开发期间缓存视图将其设置为true;在生产中默认启用视图缓存。

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

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

个人挺喜欢这个的,简洁。 返回单个路由的实例,然后您可以使用该实例来处理具有可选中间件的HTTP动词。使用app.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.use(path, callback , callback...)

这个大家经常用,挂载中间件,不多赘述。