Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 512 lines (350 sloc) 12.9 kB
bf0abf2 @tj added express.md
authored
1
2 # app
3
4 Application prototype.
5
6 # app.use()
7
8 Proxy `connect#use()` to apply settings to
9 mounted applications.
10
11 # app.engine()
12
13 Register the given template engine callback `fn`
14 as `ext`.
15
16 By default will `require()` the engine based on the
17 file extension. For example if you try to render
18 a "foo.jade" file Express will invoke the following internally:
19
20 app.engine('jade', require('jade').__express);
21
22 For engines that do not provide `.__express` out of the box,
23 or if you wish to "map" a different extension to the template engine
24 you may use this method. For example mapping the EJS template engine to
25 ".html" files
26
27 app.engine('html', require('ejs').renderFile);
28
29 In this case EJS provides a `.renderFile()` method with
30 the same signature that Express expects: `(path, options, callback)`,
31 though note that it aliases this method as `ejs.__express` internally
32 so if you're using ".ejs" extensions you dont need to do anything.
33
34 Some template engines do not follow this convention, the
35 [Consolidate.js](https://github.com/visionmedia/consolidate.js)
36 library was created to map all of node's popular template
37 engines to follow this convention, thus allowing them to
38 work seemlessly within Express.
39
40 # app.param()
41
42 Map the given param placeholder `name`(s) to the given callback(s).
43
44 Parameter mapping is used to provide pre-conditions to routes
45 which use normalized placeholders. For example a _:user_id_ parameter
46 could automatically load a user's information from the database without
47 any additional code,
48
49 The callback uses the samesignature as middleware, the only differencing
50 being that the value of the placeholder is passed, in this case the _id_
51 of the user. Once the `next()` function is invoked, just like middleware
52 it will continue on to execute the route, or subsequent parameter functions.
53
54 app.param('user_id', function(req, res, next, id){
55 User.find(id, function(err, user){
56 if (err) {
57 next(err);
58 } else if (user) {
59 req.user = user;
60 next();
61 } else {
62 next(new Error('failed to load user'));
63 }
64 });
65 });
66
67 # app.set()
68
69 Assign `setting` to `val`, or return `setting`'s value.
70
71 app.set('foo', 'bar');
72 app.get('foo');
73 // => "bar"
74
75 Mounted servers inherit their parent server's settings.
76
77 # app.enabled()
78
79 Check if `setting` is enabled (truthy).
80
81 app.enabled('foo')
82 // => false
83
84 app.enable('foo')
85 app.enabled('foo')
86 // => true
87
88 # app.disabled()
89
90 Check if `setting` is disabled.
91
92 app.disabled('foo')
93 // => true
94
95 app.enable('foo')
96 app.disabled('foo')
97 // => false
98
99 # app.enable()
100
101 Enable `setting`.
102
103 # app.disable()
104
105 Disable `setting`.
106
107 # app.configure()
108
109 Configure callback for zero or more envs,
110 when no `env` is specified that callback will
111 be invoked for all environments. Any combination
112 can be used multiple times, in any order desired.
113
114 ## Examples
115
116 app.configure(function(){
117 // executed for all envs
118 });
119
120 app.configure('stage', function(){
121 // executed staging env
122 });
123
124 app.configure('stage', 'production', function(){
125 // executed for stage and production
126 });
127
128 ## Note
129
130 These callbacks are invoked immediately, and
131 are effectively sugar for the following.
132
133 var env = process.env.NODE_ENV || 'development';
134
135 switch (env) {
136 case 'development':
137 ...
138 break;
139 case 'stage':
140 ...
141 break;
142 case 'production':
143 ...
144 break;
145 }
146
147 # app.all()
148
149 Special-cased "all" method, applying the given route `path`,
150 middleware, and callback to _every_ HTTP method.
151
152 # app.render()
153
154 Render the given view `name` name with `options`
155 and a callback accepting an error and the
156 rendered template string.
157
158 ## Example
159
160 app.render('email', { name: 'Tobi' }, function(err, html){
161 // ...
162 })
163
164 # app.listen()
165
166 Listen for connections.
167
168 A node `http.Server` is returned, with this
169 application (which is a `Function`) as its
170 callback. If you wish to create both an HTTP
171 and HTTPS server you may do so with the "http"
172 and "https" modules as shown here.
173
174 var http = require('http')
175 , https = require('https')
176 , express = require('express')
177 , app = express();
178
179 http.createServer(app).listen(80);
180 http.createServer({ ... }, app).listen(443);
181
182
183 # req
184
185 Request prototype.
186
ec2f445 @tj update
authored
187 # req.get
bf0abf2 @tj added express.md
authored
188
189 Return request header.
190
191 The `Referrer` header field is special-cased,
ec2f445 @tj update
authored
192 both `Referrer` and `Referer` are interchangeable.
bf0abf2 @tj added express.md
authored
193
194 ## Examples
195
196 req.get('Content-Type');
197 // => "text/plain"
198
199 req.get('content-type');
200 // => "text/plain"
ec2f445 @tj update
authored
201
bf0abf2 @tj added express.md
authored
202 req.get('Something');
203 // => undefined
ec2f445 @tj update
authored
204
205 Aliased as `req.header()`.
bf0abf2 @tj added express.md
authored
206
207 # req.accepts()
208
209 Check if the given `type(s)` is acceptable, returning
210 the best match when true, otherwise `undefined`, in which
211 case you should respond with 406 "Not Acceptable".
212
213 The `type` value may be a single mime type string
214 such as "application/json", the extension name
215 such as "json", a comma-delimted list such as "json, html, text/plain",
216 or an array `["json", "html", "text/plain"]`. When a list
217 or array is given the _best_ match, if any is returned.
218
219 ## Examples
220
221 // Accept: text/html
222 req.accepts('html');
223 // => "html"
224
225 // Accept: text/*, application/json
226 req.accepts('html');
227 // => "html"
228 req.accepts('text/html');
229 // => "text/html"
230 req.accepts('json, text');
231 // => "json"
232 req.accepts('application/json');
233 // => "application/json"
234
235 // Accept: text/*, application/json
236 req.accepts('image/png');
237 req.accepts('png');
238 // => undefined
239
240 // Accept: text/*;q=.5, application/json
241 req.accepts(['html', 'json']);
242 req.accepts('html, json');
243 // => "json"
244
245 # req.acceptsCharset()
246
247 Check if the given `charset` is acceptable,
248 otherwise you should respond with 406 "Not Acceptable".
249
250 # req.acceptsLanguage()
251
252 Check if the given `lang` is acceptable,
253 otherwise you should respond with 406 "Not Acceptable".
254
255 # req.param()
256
257 Return the value of param `name` when present or `defaultValue`.
258
259 - Checks body params, ex: id=12, {"id":12}
260 - Checks route placeholders, ex: _/user/:id_
261 - Checks query string params, ex: ?id=12
262
263 To utilize request bodies, `req.body`
264 should be an object. This can be done by using
265 the `connect.bodyParser()` middleware.
266
267 # req.is()
268
269 Check if the incoming request contains the "Content-Type"
270 header field, and it contains the give mime `type`.
271
272 ## Examples
273
274 // With Content-Type: text/html; charset=utf-8
275 req.is('html');
276 req.is('text/html');
277 req.is('text/*');
278 // => true
279
280 // When Content-Type is application/json
281 req.is('json');
282 req.is('application/json');
283 req.is('application/*');
284 // => true
285
286 req.is('html');
287 // => false
288
289 Now within our route callbacks, we can use to to assert content types
290 such as "image/jpeg", "image/png", etc.
291
292 app.post('/image/upload', function(req, res, next){
293 if (req.is('image/*')) {
294 // do something
295 } else {
296 next();
297 }
298 });
299
300
301 # res
302
303 Response prototype.
304
305 # res.status()
306
307 Set status `code`.
308
309 # res.send()
310
311 Send a response.
312
313 ## Examples
314
315 res.send(new Buffer('wahoo'));
316 res.send({ some: 'json' });
317 res.send('<p>some html</p>');
318 res.send(404, 'Sorry, cant find that');
319 res.send(404);
320
321 # res.json()
322
323 Send JSON response.
324
325 ## Examples
326
327 res.json(null);
328 res.json({ user: 'tj' });
329 res.json(500, 'oh noes!');
330 res.json(404, 'I dont have that');
331
332 # res.sendfile()
333
334 Transfer the file at the given `path`.
335
336 Automatically sets the _Content-Type_ response header field.
337 The callback `fn(err)` is invoked when the transfer is complete
338 or when an error occurs. Be sure to check `res.sentHeader`
339 if you wish to attempt responding, as the header and some data
340 may have already been transferred.
341
342 ## Options
343
344 - `maxAge` defaulting to 0
345 - `root` root directory for relative filenames
346
347 ## Examples
348
349 The following example illustrates how `res.sendfile()` may
350 be used as an alternative for the `static()` middleware for
351 dynamic situations. The code backing `res.sendfile()` is actually
352 the same code, so HTTP cache support etc is identical.
353
354 app.get('/user/:uid/photos/:file', function(req, res){
355 var uid = req.params.uid
356 , file = req.params.file;
357
358 req.user.mayViewFilesFrom(uid, function(yes){
359 if (yes) {
360 res.sendfile('/uploads/' + uid + '/' + file);
361 } else {
362 res.send(403, 'Sorry! you cant see that.');
363 }
364 });
365 });
366
367 # res.download()
368
369 Transfer the file at the given `path` as an attachment.
370
371 Optionally providing an alternate attachment `filename`,
372 and optional callback `fn(err)`. The callback is invoked
373 when the data transfer is complete, or when an error has
374 ocurred. Be sure to check `res.headerSent` if you plan to respond.
375
376 # res.format()
377
378 Respond to the Acceptable formats using an `obj`
379 of mime-type callbacks.
380
381 This method uses `req.accepted`, an array of
382 acceptable types ordered by their quality values.
383 When "Accept" is not present the _first_ callback
384 is invoked, otherwise the first match is used. When
385 no match is performed the server responds with
386 406 "Not Acceptable".
387
388 Content-Type is set for you, however if you choose
389 you may alter this within the callback using `res.type()`
390 or `res.set('Content-Type', ...)`.
391
392 res.format({
393 'text/plain': function(){
394 res.send('hey');
395 },
396
397 'text/html': function(){
398 res.send('<p>hey</p>');
399 },
400
401 'appliation/json': function(){
402 res.send({ message: 'hey' });
403 }
404 });
405
406 In addition to canonicalized MIME types you may
407 ## also use extnames mapped to these types
408
409 res.format({
410 text: function(){
411 res.send('hey');
412 },
413
414 html: function(){
415 res.send('<p>hey</p>');
416 },
417
418 json: function(){
419 res.send({ message: 'hey' });
420 }
421 });
422
423 # res.attachment()
424
425 Set _Content-Disposition_ header to _attachment_ with optional `filename`.
426
427 # res.set()
428
429 Set header `field` to `val`, or pass
430 an object of of header fields.
431
432 ## Examples
433
434 res.set('Accept', 'application/json');
435 res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
436
437 # res.get()
438
439 Get value for header `field`.
440
441 # res.clearCookie()
442
443 Clear cookie `name`.
444
445 # res.signedCookie()
446
447 Set a signed cookie with the given `name` and `val`.
448 See `res.cookie()` for details.
449
450 # res.cookie()
451
452 Set cookie `name` to `val`, with the given `options`.
453
454 ## Options
455
456 - `maxAge` max-age in milliseconds, converted to `expires`
457 - `path` defaults to "/"
458
459 ## Examples
460
461 // "Remember Me" for 15 minutes
462 res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
463
464 // save as above
465 res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
466
467 # res.redirect()
468
469 Redirect to the given `url` with optional response `status`
470 defaulting to 302.
471
472 The given `url` can also be the name of a mapped url, for
473 example by default express supports "back" which redirects
474 to the _Referrer_ or _Referer_ headers or "/".
475
476 ## Examples
477
478 res.redirect('/foo/bar');
479 res.redirect('http://example.com');
480 res.redirect(301, 'http://example.com');
481 res.redirect('../login'); // /blog/post/1 -> /blog/login
482
483 ## Mounting
484
485 When an application is mounted, and `res.redirect()`
486 is given a path that does _not_ lead with "/". For
487 example suppose a "blog" app is mounted at "/blog",
488 the following redirect would result in "/blog/login":
489
490 res.redirect('login');
491
492 While the leading slash would result in a redirect to "/login":
493
494 res.redirect('/login');
495
496 # res.render()
497
498 Render `view` with the given `options` and optional callback `fn`.
499 When a callback function is given a response will _not_ be made
500 automatically, otherwise a response of _200_ and _text/html_ is given.
501
502 ## Options
503
504 - `status` Response status code (`res.statusCode`)
505 - `charset` Set the charset (`res.charset`)
506
507 ## Reserved locals
508
509 - `cache` boolean hinting to the engine it should cache
510 - `filename` filename of the view being rendered
511
Something went wrong with that request. Please try again.