express的API总共分为五类,分别是Express()、application、request、response、router等。

一、Express()

1. express.json()

内置中间件。由于request.body的内容基于用户的输入,因此该对象中的所有属性和值都不可信,应在可信之前进行验证。例如,request.body.foo.toString()可能以多种方式失败,例如 foo可能不存在或可能不是字符串,并且toString可能不是函数,而是字符串或其他用户输入。express.json()使用body解析器解析带有JSON负载的传入请求,返回仅解析JSON并且仅查看Content-Type标头与type选项匹配的请求的中间件。该解析器接受主体的任何Unicode编码,并支持gzipdeflate编码的自动填充。例:

  1. const express = require('express')
  2. const app = express()
  3. app.use(express.json())
  4. app.use((request,response,next)=>{
  5. console.log(request.body)
  6. response.send('hi');
  7. request.on('data',(chunk)=>{
  8. console..log(chunk.toString())
  9. })
  10. next()
  11. })

上代码中, request.body会被处理然后打印出来,而 chunk.toString() 则会被忽略,因为返回数据已被上面捕获处理。

2. express.static(root,[options])

root参数指定要从其提供静态资源的根目录。该功能通过req.url与提供的root目录结合来确定要提供的文件。当找不到文件时,它不会发送404响应,而是调用next() 移至下一个中间件,从而可以进行堆栈和回退。

  1. app.use(express.static('yyy'))

如果在yyy路径找到文件,返回该静态文件,如果没有,调用next()进入下一个中间件。

二、app.xxx

1. app.set(name, value)

设置namevalue。您可以存储所需的任何值,但是可以使用某些名称来配置服务器的行为。这些特殊名称在应用程序设置表中列出。例:

  1. app.set('case sensitive routing',true)//默认false,资源访问路径是是否对大小写敏感。set必须写在所有中间件的最前面。
  2. app.set('views','test') //设备默认视图的目录为test;
  3. app.set('view engine','pug') //设备默认引擎为pug;
  4. app.get('/style.css',(resquest,response,next)=>{
  5. resquest.send('style.css')
  6. })

上述代码执行中,如果访问路径为xxx/STYLE.css,将不会得到任何响应.

2. app.get()、app.post()、app.put()、app.delete()

页面被请求时的响应方法。例:

  1. app.get('/test',(req,res,next)=>{
  2. res.send('get /test')
  3. })
  4. app.post('/test',(req,res,next)=>{
  5. res.send('post /test')
  6. })
  7. app.put('/test',(req,res,next)=>{
  8. res.send('put /test')
  9. })
  10. app.delete('/test',(req,res,next)=>{
  11. res.send('delete /test')
  12. })

中间件之间获取参数的方法:

  1. //app.js
  2. const express = require('express')
  3. const app = express()
  4. const fn1 = require('./fn1')
  5. app.locals.title = '这是标题'
  6. app.use(fn1)
  1. //fn1.js
  2. const fn1 = (req,res,next)=>{
  3. res.render('test',{pageTitle:req.app.locals.title}) //app.locals默认附加在req中
  4. }
  5. module.exports = fn1

三、Request.xxx

1. request.params

此属性是一个对象,其中包含映射到命名路由“ parameters”的属性。例如,请求路径/user/:name,则“ name”属性可以被req.params.name获取。该对象默认为{}。例:

  1. // GET /users/1
  2. app.get('/users/:id',(req,res,next)=>{
  3. console.log(req.params) //=> 此处返回{id:1}
  4. })


2. request.path

返回请求路径, 不包含查询字符串。例:

  1. // example.com/users?sort=desc
  2. console.dir(req.path)
  3. // => '/users'

3. request.query

返回每个查询字符串参数的属性。例:

  1. // GET /search?q=tobi+ferret
  2. console.dir(req.query.q)
  3. // => 'tobi ferret'
  4. // GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
  5. console.dir(req.query.order)
  6. // => 'desc'
  7. console.dir(req.query.shoe.color)
  8. // => 'blue'
  9. console.dir(req.query.shoe.type)
  10. // => 'converse'
  11. // GET /shoes?color[]=blue&color[]=black&color[]=red
  12. console.dir(req.query.color)
  13. // => ['blue', 'black', 'red']

四、Response.xxx

1. response.set(field [, value])

响应头设置。要一次设置多个字段,请传递一个对象作为参数。例:

  1. res.set('Content-Type', 'text/plain')
  2. res.set({
  3. 'Content-Type': 'text/plain',
  4. 'Content-Length': '123',
  5. ETag: '12345'
  6. })

它的别名为res.header(field [, value])

2. res.format(object)

可以根据请求头的accept值判断返回不同的响应。例:

  1. res.format({
  2. 'text/plain': function () {
  3. res.send('hey')
  4. },
  5. 'text/html': function () {
  6. res.send('<p>hey</p>')
  7. },
  8. 'application/json': function () {
  9. res.send({ message: 'hey' })
  10. },
  11. default: function () {
  12. // log the request and respond with 406
  13. res.status(406).send('Not Acceptable')
  14. }
  15. })

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

地址重定向到path。并指定当前status,如果未指定,则status默认为302。例:

  1. res.redirect('/foo/bar')
  2. res.redirect('http://example.com')
  3. res.redirect(301, 'http://example.com')
  4. res.redirect('../login')

重定向可是指向其他站点网址:

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

重定向可以相对于主机名的根目录。例如,如果打开[http://example.com/admin/post/new](http://example.com/admin/post/new),则执行以下内容将重定向到URL [http://example.com/admin](http://example.com/admin)

  1. res.redirect('/admin')

重定向可以相对于当前URL。例如,从[http://example.com/blog/admin/](http://example.com/blog/admin/)(注意结尾的斜杠),以下内容将重定向到URL [http://example.com/blog/admin/post/new](http://example.com/blog/admin/post/new)

  1. res.redirect('post/new')

如果结尾不存在斜杠,post/new从重定向到[http://example.com/blog/admin](http://example.com/blog/admin)(不带斜杠),将重定向到[http://example.com/blog/post/new](http://example.com/blog/post/new)

重定向也可以作用于相对路径,如:

  1. res.redirect('..')

[http://example.com/admin/post/new](http://example.com/admin/post/new),将重定向到 [http://example.com/admin/post](http://example.com/admin/post)

五、Router

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

可用于全局路由逻辑映射到特定路径前缀或对路由的任意匹配项进行下一步操作。如跳转前的身份验证:

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

或者是白名单功能:

  1. router.all('/api/*', requireAuthentication) //限制'/api'为前缀的路径

2. router.METHOD(path, [callback, …] callback)

路由的请求方法设置,如:router.get()router.post()router.put()

  1. router.get('/', function (req, res) {
  2. res.send('hello world')
  3. })

3. router.param(name, callback)

路由参数。与app.param()不同的是,它不接受数组成为路由参数。下列例子中,当路径中存在 :user ,可以映射相应的加载逻辑,或获取参数以进行下一步操作。

  1. router.param('user', function (req, res, next, id) {
  2. // try to get the user details from the User model and attach it to the request object
  3. User.find(id, function (err, user) {
  4. if (err) {
  5. next(err)
  6. } else if (user) {
  7. req.user = user
  8. next()
  9. } else {
  10. next(new Error('failed to load user'))
  11. }
  12. })
  13. })

4. router.route(path)

指定单个路由实例,加载中间件以做特定路由的操作。例:

  1. var router = express.Router()
  2. router.param('user_id', function (req, res, next, id) {
  3. // sample user, would actually fetch from DB, etc...
  4. req.user = {
  5. id: id,
  6. name: 'TJ'
  7. }
  8. next()
  9. })
  10. router.route('/users/:user_id')
  11. .all(function (req, res, next) {
  12. // runs for all HTTP verbs first
  13. // think of it as route specific middleware!
  14. next()
  15. })
  16. .get(function (req, res, next) {
  17. res.json(req.user)
  18. })
  19. .put(function (req, res, next) {
  20. // just an example of maybe updating the user
  21. req.user.name = req.params.name
  22. // save user ... etc
  23. res.json(req.user)
  24. })
  25. .post(function (req, res, next) {
  26. next(new Error('not implemented'))
  27. })
  28. .delete(function (req, res, next) {
  29. next(new Error('not implemented'))
  30. })

这种方法针对单个/users/:user_id路径,并为之添加了单独的处理操作。

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

类似于app.use(),以下是例子:

  1. var express = require('express')
  2. var app = express()
  3. var router = express.Router()
  4. //所有的请求都会先经过该中间件进行逻辑操作
  5. router.use(function (req, res, next) {
  6. console.log('%s %s %s', req.method, req.url, req.path)
  7. next()
  8. })
  9. // 仅当路径以/bar开头时才会调用该方法
  10. router.use('/bar', function (req, res, next) {
  11. // ... maybe some additional /bar logging ...
  12. next()
  13. })
  14. // 路由中总是会调用的方法
  15. router.use(function (req, res, next) {
  16. res.send('Hello World')
  17. })
  18. app.use('/foo', router)
  19. app.listen(3000)

要注意的是,router.use()的定义顺序非常重要,它总是从上往下顺序调用,用顺序确定执行优先级。举例来说,如果定义一个记录器,它通常会写在最前面,这样每个请求才会都被记录下来。

现在,假设您想忽略对静态文件的日志记录请求,但是继续记录在之后定义的路由和中间件logger()。您只需express.static()在添加记录器中间件之前将调用移至顶部即可:

  1. router.use(express.static(path.join(__dirname, 'public')))
  2. router.use(logger())
  3. router.use(function (req, res) {
  4. res.send('Hello')
  5. })