DEV Community

Lam
Lam

Posted on

4 2

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

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay