Node.js:ExpressWeb
API接口 app()
```js var express = require('express') var app = express() ``` ### app.locals app.locals对象的属性是应用程序中的局部变量。 设置后,app.locals属性的值将在应用程序的整个生命周期内保持不变,而res.locals的属性仅在请求的生命周期内有效。 您可以访问应用程序中呈现的模板中的局部变量。这对于为模板提供帮助函数以及应用程序级数据非常有用。本地变量可通过req.app.locals在中间件中使用。 ```js //设置 app.locals.title = 'My App'; app.locals.strftime = require('strftime'); app.locals.email = 'me@myapp.com'; //获取 console.dir(app.locals.title); // => 'My App' console.dir(app.locals.email); // => 'me@myapp.com' ``` ### app.mountpath app.mountpath属性包含一个或多个子应用程序所安装的路径模式。 子应用程序是express的一个实例,可用于处理对路由的请求。 ```js 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.on('mount', callback(parent)) 当子应用程序装载到父应用程序上时,将在子应用程序上激发装载事件。父应用程序被传递给回调函数。 子应用程序将: 不继承具有默认值的设置的值。您必须在子应用程序中设置值。 继承没有默认值的设置的值。 ```js 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) ``` ### app.all(path, callback [, callback ...]) 这种方法与标准应用程序类似。METHOD()方法,但它匹配所有HTTP谓词。 ```js app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...') next() // pass control to the next handler }) app.all('*', requireAuthentication) app.all('*', loadUser) app.all('/api/*', requireAuthentication) ``` ### app.delete(path, callback [, callback ...]) 使用指定的回调函数将HTTP DELETE请求路由到指定的路径。 ```js app.delete('/', function (req, res) { res.send('DELETE request to homepage') }) ``` ### app.disable(name) 将应用程序设置表中的属性设置为false。app.set('foo',false)与调用app.disable('foo')相同。 ```js app.disable('trust proxy') app.get('trust proxy') // => false ``` ### app.disabled(name) 检查指定的属性是否被设置为false,如果是,则返回true。 ```js app.disabled('trust proxy') // => true ``` ### app.enable(name) 将应用程序设置表中的属性设置为true。app.set('foo',true)与调用app.enable('foo')相同。 ```js app.enable('trust proxy') app.get('trust proxy') // => true ``` ### app.enabled(name) 检查指定的属性是否被设置为true,如果是,则返回true。 ```js app.enabled('trust proxy') // => false app.enable('trust proxy') app.enabled('trust proxy') // => true ``` ### app.engine(ext, callback) 将给定的模板引擎回调注册为ext。 默认情况下,Express将require()基于文件扩展名的引擎。例如,如果您尝试渲染一个“foo.pug”文件,Express会在内部调用以下内容,并在后续调用中缓存require()以提高性能。 ```javascript app.engine('pug', require('pug').__express) ``` 对于不提供的引擎,请使用此方法__express开箱即用,或者如果您希望将不同的扩展“映射”到模板引擎。例如,要将EJS模板引擎映射到“.html”文件: ```js app.engine('html', require('ejs').renderFile) ``` 在这种情况下,EJS提供了一个.renderFile()方法,该方法具有Express期望的相同签名:(路径、选项、回调),但请注意,它将该方法别名为EJS__内部表达,因此如果您使用“.ejs”扩展,则无需执行任何操作。 某些模板引擎不遵循此约定。consolidate.js库映射Node模板引擎以遵循此约定,因此它们可以与Express无缝配合。 ```js var engines = require('consolidate') app.engine('haml', engines.haml) app.engine('html', engines.hogan) ``` ### app.get(name) 返回name应用程序设置的值,其中name是应用程序设置表中的字符串之一。例如: ```javascript app.get('title') // => undefined app.set('title', 'My Site') app.get('title') // => "My Site" ``` ### app.get(path, callback [, callback ...]) 使用指定的回调函数将HTTP GET请求路由到指定的路径。 ```javascript app.get('/', function (req, res) { res.send('GET request to homepage') }) ``` ### app.listen(path, [callback]) 启动UNIX套接字并侦听给定路径上的连接。此方法与Node的http.Server.listen()相同。 ```javascript var express = require('express') var app = express() app.listen('/tmp/sock') ``` ### app.listen(port[, host[, backlog]]) 设置监听的端口 ```javascript var express = require('express') var https = require('https') var http = require('http') var app = express() app.listen(3000) http.createServer(app).listen(80) https.createServer(options, app).listen(443) ``` ### app.METHOD(path, callback [, callback ...]) 路由HTTP请求,其中METHOD是请求的HTTP方法,如GET、PUT、POST等,小写。因此,实际的方法有app.get()、app.post()、app.put()等。 ### app.param([name], callback) 向路由参数添加回调触发器,其中name是参数的名称或它们的数组,callback是回调函数。回调函数的参数依次是请求对象、响应对象、下一个中间件、参数值和参数名称。 如果name是一个数组,则会按照声明的顺序为其中声明的每个参数注册回调触发器。此外,对于除最后一个参数外的每个已声明参数,回调中对next的调用将调用下一个已声明参数的回调。对于最后一个参数,对next的调用将调用当前正在处理的路由的下一个中间件,就像name只是一个字符串一样。 例如,当:user出现在路由路径中时,您可以映射用户加载逻辑以自动向路由提供req.user,或者对参数输入执行验证。 ```javascript 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回调函数是定义它们的路由器的本地函数。它们不会被安装的应用程序或路由器继承。因此,在应用程序上定义的参数回调将仅由在应用程序路由上定义的路由参数触发。 所有param回调都将在出现param的任何路由的任何处理程序之前调用,并且在一个请求-响应周期中,即使参数在多个路由中匹配,它们也只会被调用一次,如以下示例所示。 ```javascript 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() }) ////// app.param(function (param, option) { return function (req, res, next, val) { if (val === option) { next() } else { next('route') } } }) ////// app.param(function (param, validator) { return function (req, res, next, val) { if (validator(val)) { next() } else { next('route') } } }) ``` ### app.path() ```javascript var app = express() var blog = express() var blogAdmin = express() app.use('/blog', blog) blog.use('/admin', blogAdmin) console.dir(app.path()) // '' console.dir(blog.path()) // '/blog' console.dir(blogAdmin.path()) // '/blog/admin' ``` ### app.post(path, callback [, callback ...]) ```javascript app.post('/', function (req, res) { res.send('POST request to homepage') }) ``` ### app.put(path, callback [, callback ...]) ```javascript app.put('/', function (req, res) { res.send('PUT request to homepage') }) ``` ### app.render(view, [locals], callback) ```javascript app.render('email', function (err, html) { // ... }) app.render('email', { name: 'Tobi' }, function (err, html) { // ... }) ``` ### app.route(path) ```javascript 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) 将设置名称指定给值。您可以存储所需的任何值,但某些名称可以用于配置服务器的行为。这些特殊名称列在应用程序设置表中。 ```javascript app.set('title', 'My Site') app.get('title') // "My Site" ``` ### app.use([path,] callback [, callback...]) 将指定的一个或多个中间件函数装载到指定的路径:当请求的路径的基与路径匹配时,执行中间件函数。 ```javascript app.use(function (req, res, next) { console.log('Time: %d', Date.now()) next() }) app.use('/abcd', function (req, res, next) { next() }) app.use('/abc?d', function (req, res, next) { next() }) app.use('/ab+cd', function (req, res, next) { next() }) app.use('/ab*cd', function (req, res, next) { next() }) app.use('/a(bc)?d', function (req, res, next) { next() }) app.use(/\/abc|\/xyz/, function (req, res, next) { next() }) app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { next() }) ``` ```javascript app.use(express.static(path.join(__dirname, 'public'))) app.use('/static', express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'public'))) app.use(logger()) app.use(express.static(path.join(__dirname, 'public'))) app.use(express.static(path.join(__dirname, 'files'))) app.use(express.static(path.join(__dirname, 'uploads'))) ```
顶部
收展
底部
[TOC]
目录
Express/Node 入门
路由
中间件
API接口 express()
API接口 app()
API接口 res()
API接口 Router()
数据库操作 ODM mongoose
相关推荐
Node.js教程:新手入门
Node.js接口
朴灵《深入浅出 Node.js》