DEV Community

Lam
Lam

Posted on

Express.Js Cheat Sheet

[Request & response] Response

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

[Request & response] Request

// 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]
Enter fullscreen mode Exit fullscreen mode
// GET /search?q=tobi+ferret
req.query.q // => "tobi ferret"
Enter fullscreen mode Exit fullscreen mode
req.cookies
Enter fullscreen mode Exit fullscreen mode
req.accepted
// [ { value: 'application/json', quality: 1, type: 'application', subtype: 'json' },
//   { value: 'text/html', quality: 0.5, type: 'text',subtype: 'html' } ]
Enter fullscreen mode Exit fullscreen mode
req.is('html')
req.is('text/html')
Enter fullscreen mode Exit fullscreen mode
req.headers
req.headers['host']
req.headers['user-agent']
req.headers['accept-encoding']
req.headers['accept-language']
Enter fullscreen mode Exit fullscreen mode

Helpers

app.locals({
  title: "MyApp",
})
Enter fullscreen mode Exit fullscreen mode

Wares

app.use(express.static(__dirname + '/public'))
app.use(express.logger())
Enter fullscreen mode Exit fullscreen mode

Config

app.configure('production', function() {
  app.set...
})
Enter fullscreen mode Exit fullscreen mode

Env

app.get('env')
Enter fullscreen mode Exit fullscreen mode

Settings

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

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

app.enabled('trust proxy') //=> true
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (0)