Cheat Sheet速查表
跳转到主要内容

Express.js 速查表

本文根据 Devhints / Express.js 翻译。代码示例及版本范围沿用原文。

设置

app.set('x', 'yyy')
app.get('x') //=> 'yyy'

app.enable('trust proxy')
app.disable('trust proxy')

app.enabled('trust proxy') //=> true

环境 (Env)

app.get('env')

配置

app.configure('production', function() {
  app.set...
})

中间件 (Wares)

app.use(express.static(__dirname + '/public'))
app.use(express.logger())

辅助方法 (Helpers)

app.locals({
  title: "MyApp",
})

请求与响应

请求

// GET  /user/tj
req.path         //=> "/user/tj"
req.url          //=> "/user/tj"
req.xhr          //=> true|false
req.method       //=> "GET"
req.params
req.params.name  //=> "tj"
req.params[0]
// GET /search?q=tobi+ferret
req.query.q // => "tobi ferret"
req.cookies
req.accepted
// [ { value: 'application/json', quality: 1, type: 'application', subtype: 'json' },
//   { value: 'text/html', quality: 0.5, type: 'text',subtype: 'html' } ]
req.is('html')
req.is('text/html')
req.headers
req.headers['host']
req.headers['user-agent']
req.headers['accept-encoding']
req.headers['accept-language']

响应

res.redirect('/')
res.redirect(301, '/')
res.set('Content-Type', 'text/html')
res.send('hi')
res.send(200, 'hi')
res.json({ a: 2 })