cheatsheets/express.md

109 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2013-10-14 02:36:58 +00:00
---
2013-05-29 12:19:07 +00:00
title: Express.js
2015-11-24 05:02:17 +00:00
category: JavaScript libraries
2013-05-29 12:19:07 +00:00
---
### Settings
2018-05-16 00:01:38 +00:00
```js
app.set('x', 'yyy')
app.get('x') //=> 'yyy'
2013-05-29 12:19:07 +00:00
2018-05-16 00:01:38 +00:00
app.enable('trust proxy')
app.disable('trust proxy')
2013-05-29 12:19:07 +00:00
2018-05-16 00:01:38 +00:00
app.enabled('trust proxy') //=> true
```
2013-05-29 12:19:07 +00:00
### Env
2018-05-16 00:01:38 +00:00
```js
app.get('env')
```
2013-05-29 12:19:07 +00:00
### Config
2018-05-16 00:01:38 +00:00
```js
app.configure('production', function() {
app.set...
})
```
2013-05-29 12:19:07 +00:00
### Wares
2018-05-16 00:01:38 +00:00
```js
app.use(express.static(__dirname + '/public'))
app.use(express.logger())
```
2013-05-29 12:19:07 +00:00
### Helpers
2018-05-16 00:01:38 +00:00
```js
app.locals({
title: "MyApp",
})
```
2013-05-29 12:19:07 +00:00
2018-05-16 00:01:38 +00:00
## Request & response
2013-05-29 12:19:07 +00:00
2018-05-16 00:01:38 +00:00
### Request
2013-05-29 12:19:07 +00:00
2018-05-16 00:01:38 +00:00
```js
// 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]
```
```js
// GET /search?q=tobi+ferret
req.query.q // => "tobi ferret"
```
```js
req.cookies
```
```js
req.accepted
// [ { value: 'application/json', quality: 1, type: 'application', subtype: 'json' },
// { value: 'text/html', quality: 0.5, type: 'text',subtype: 'html' } ]
```
```js
req.is('html')
req.is('text/html')
```
```js
req.headers
req.headers['host']
req.headers['user-agent']
req.headers['accept-encoding']
req.headers['accept-language']
```
### Response
```js
res.redirect('/')
res.redirect(301, '/')
```
```js
res.set('Content-Type', 'text/html')
```
```js
res.send('hi')
res.send(200, 'hi')
```
```js
res.json({ a: 2 })
```