Skip to content
Myr

response.js

This file

Path

lib/response.js

422 lines · 10.1 KiB · JavaScript

Last changed by

misc refactorTj Holowaychukbefore adoption490584c

History of this file

Take it

The walk stopped after 200 commits: lines older than d5b7a40 point at it.

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 1–19why, one step back
1
2/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13 , http = require('http')14 , path = require('path')15 , connect = require('connect')16 , utils = connect.utils17 , parseRange = require('./utils').parseRange18 , res = http.ServerResponse.prototype19 , send = connect.static.send

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 20–22why, one step back
20 , mime = require('mime')
21 , basename = path.basename22 , join = path.join;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 23–54why, one step back
23
24/**25 * Send a response with the given `body` and optional `headers` and `status` code.26 *27 * Examples:28 *29 * res.send();30 * res.send(new Buffer('wahoo'));31 * res.send({ some: 'json' });32 * res.send('<p>some html</p>');33 * res.send('Sorry, cant find that', 404);34 * res.send('text', { 'Content-Type': 'text/plain' }, 201);35 * res.send(404);36 *37 * @param {String|Object|Number|Buffer} body or status38 * @param {Object|Number} headers or status39 * @param {Number} status40 * @return {ServerResponse}41 * @api public42 */4344res.send = function(body, headers, status){45 // allow status as second arg46 if ('number' == typeof headers) {47 status = headers,48 headers = null;49 }5051 // default status52 status = status || this.statusCode;5354 // allow 0 args as 204

res.send(undefined) returns a 204Aaron Heckmannbefore adoption673ba22

line 55why, one step back
55 if (!arguments.length || undefined === body) body = status = 204;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 56–66why, one step back
56
57 // determine content type58 switch (typeof body) {59 case 'number':60 if (!this.header('Content-Type')) {61 this.contentType('.txt');62 }63 body = http.STATUS_CODES[status = body];64 break;65 case 'string':66 if (!this.header('Content-Type')) {

JSON and JSONP default to UTF-8 in the same way as HTML. Closes #632.Daniel Shawbefore adoption3afbcd0

line 67why, one step back
67 this.charset = this.charset || 'utf-8';

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 68–70why, one step back
68 this.contentType('.html');
69 }70 break;

Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3

line 71why, one step back
71 case 'boolean':

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 72–78why, one step back
72 case 'object':
73 if (Buffer.isBuffer(body)) {74 if (!this.header('Content-Type')) {75 this.contentType('.bin');76 }77 } else {78 if (!this.header('Content-Type')) {

JSON and JSONP default to UTF-8 in the same way as HTML. Closes #632.Daniel Shawbefore adoption3afbcd0

line 79why, one step back
79 this.charset = this.charset || 'utf-8';

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 80–83why, one step back
80 this.contentType('.json');
81 }82 body = JSON.stringify(body);83 if (this.req.query.callback && this.app.set('jsonp callback')) {

JSON and JSONP default to UTF-8 in the same way as HTML. Closes #632.Daniel Shawbefore adoption3afbcd0

line 84why, one step back
84 this.charset = this.charset || 'utf-8';

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 85–108why, one step back
85 this.header('Content-Type', 'text/javascript');
86 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';87 }88 }89 break;90 }9192 // populate Content-Length93 if (!this.header('Content-Length')) {94 this.header('Content-Length', Buffer.isBuffer(body)95 ? body.length96 : Buffer.byteLength(body));97 }9899 // merge headers passed100 if (headers) {101 var fields = Object.keys(headers);102 for (var i = 0, len = fields.length; i < len; ++i) {103 var field = fields[i];104 this.header(field, headers[field]);105 }106 }107108 // strip irrelevant headers

miscTj Holowaychukbefore adoption9d498ba

line 109why, one step back
109 if (204 == status) {

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 110–135why, one step back
110 this.removeHeader('Content-Type');
111 this.removeHeader('Content-Length');112 }113114 // respond115 this.statusCode = status;116 this.end('HEAD' == this.req.method ? undefined : body);117};118119/**120 * Transfer the file at the given `path`. Automatically sets 121 * the _Content-Type_ response header field. `next()` is called122 * when `path` is a directory, or when an error occurs.123 *124 * Options:125 *126 * - `maxAge` defaulting to 0127 * - `root` root directory for relative filenames128 *129 * @param {String} path130 * @param {Object|Function} options or fn131 * @param {Function} fn132 * @api public133 */134135res.sendfile = function(path, options, fn){

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 136why, one step back
136 var next = this.req.next;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 137–144why, one step back
137 options = options || {};
138139 // support function as second arg140 if ('function' == typeof options) {141 fn = options;142 options = {};143 }144

Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608

line 145why, one step back
145 options.path = encodeURIComponent(path);

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

line 146why, one step back
146 options.callback = fn;

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 147why, one step back
147 send(this.req, this, next, options);

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 148–181why, one step back
148};
149150/**151 * Set _Content-Type_ response header passed through `mime.lookup()`.152 *153 * Examples:154 *155 * var filename = 'path/to/image.png';156 * res.contentType(filename);157 * // res.headers['Content-Type'] is now "image/png"158 *159 * res.contentType('.html');160 * res.contentType('html');161 * res.contentType('json');162 * res.contentType('png');163 *164 * @param {String} type165 * @return {String} the resolved mime type166 * @api public167 */168169res.contentType = function(type){170 return this.header('Content-Type', mime.lookup(type));171};172173/**174 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.175 *176 * @param {String} filename177 * @return {ServerResponse}178 * @api public179 */180181res.attachment = function(filename){

auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571

line 182why, one step back
182 if (filename) this.contentType(filename);

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

line 183why, one step back
183 this.header('Content-Disposition', filename

misc refactoringTj Holowaychukbefore adoption70e6baf

line 184why, one step back
184 ? 'attachment; filename="' + basename(filename) + '"'

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 185–190why, one step back
185 : 'attachment');
186 return this;187};188189/**190 * Transfer the file at the given `path`, with optional

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

lines 191–192why, one step back
191 * `filename` as an attachment and optional callback `fn(err)`,
192 * and optional `fn2(err)` which is invoked when an error has

typoTj Holowaychukbefore adoption0cbb1f6

line 193why, one step back
193 * occurred after header has been sent.

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 194–197why, one step back
194 *
195 * @param {String} path196 * @param {String|Function} filename or fn197 * @param {Function} fn

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 198why, one step back
198 * @param {Function} fn2

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 199–201why, one step back
199 * @api public
200 */201

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 202why, one step back
202res.download = function(path, filename, fn, fn2){

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 203–206why, one step back
203 var self = this;
204205 // support callback as second arg206 if ('function' == typeof filename) {

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 207why, one step back
207 fn2 = fn;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 208–213why, one step back
208 fn = filename;
209 filename = null;210 }211212 // transfer the file213 this.attachment(filename || path).sendfile(path, function(err){

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 214why, one step back
214 var sentHeader = self._header;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

line 215why, one step back
215 if (err) {

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

lines 216–217why, one step back
216 if (!sentHeader) self.removeHeader('Content-Disposition');
217 if (sentHeader) {

misc refactorTj Holowaychukbefore adoptionaa68581

line 218why, one step back
218 fn2 && fn2(err);

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

lines 219–225why, one step back
219 } else if (fn) {
220 fn(err);221 } else {222 self.req.next(err);223 }224 } else if (fn) {225 fn();

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 226–251why, one step back
226 }
227 });228};229230/**231 * Set or get response header `name` with optional `val`.232 *233 * @param {String} name234 * @param {String} val235 * @return {String}236 * @api public237 */238239res.header = function(name, val){240 if (val === undefined) {241 return this.getHeader(name);242 } else {243 this.setHeader(name, val);244 return val;245 }246};247248/**249 * Clear cookie `name`.250 *251 * @param {String} name

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

line 252why, one step back
252 * @param {Object} options

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 253–255why, one step back
253 * @api public
254 */255

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

lines 256–260why, one step back
256res.clearCookie = function(name, options){
257 var opts = { expires: new Date(1) };258 this.cookie(name, '', options259 ? utils.merge(options, opts)260 : opts);

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 261–362why, one step back
261};
262263/**264 * Set cookie `name` to `val`, with the given `options`.265 *266 * Options:267 *268 * - `maxAge` max-age in milliseconds, converted to `expires`269 *270 * Examples:271 *272 * // "Remember Me" for 15 minutes273 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });274 *275 * // save as above276 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })277 *278 * @param {String} name279 * @param {String} val280 * @param {Options} options281 * @api public282 */283284res.cookie = function(name, val, options){285 options = options || {};286 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);287 var cookie = utils.serializeCookie(name, val, options);288 this.header('Set-Cookie', cookie);289};290291/**292 * Redirect to the given `url` with optional response `status`293 * defauling to 302.294 *295 * The given `url` can also be the name of a mapped url, for296 * example by default express supports "back" which redirects297 * to the _Referrer_ or _Referer_ headers or the application's298 * "home" setting. Express also supports "home" out of the box,299 * which can be set via `app.set('home', '/blog');`, and defaults300 * to '/'.301 *302 * Redirect Mapping:303 * 304 * To extend the redirect mapping capabilities that Express provides,305 * we may use the `app.redirect()` method:306 * 307 * app.redirect('google', 'http://google.com');308 * 309 * Now in a route we may call:310 *311 * res.redirect('google');312 *313 * We may also map dynamic redirects:314 *315 * app.redirect('comments', function(req, res){316 * return '/post/' + req.params.id + '/comments';317 * });318 *319 * So now we may do the following, and the redirect will dynamically adjust to320 * the context of the request. If we called this route with _GET /post/12_ our321 * redirect _Location_ would be _/post/12/comments_.322 *323 * app.get('/post/:id', function(req, res){324 * res.redirect('comments');325 * });326 *327 * Unless an absolute `url` is given, the app's mount-point328 * will be respected. For example if we redirect to `/posts`,329 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.330 *331 * @param {String} url332 * @param {Number} code333 * @api public334 */335336res.redirect = function(url, status){337 var app = this.app338 , req = this.req339 , base = app.set('home') || '/'340 , status = status || 302341 , body;342343 // Setup redirect map344 var map = {345 back: req.header('Referrer', base)346 , home: base347 };348349 // Support custom redirect map350 map.__proto__ = app.redirects;351352 // Attempt mapped redirect353 var mapped = 'function' == typeof map[url]354 ? map[url](req, this)355 : map[url];356357 // Perform redirect358 url = mapped || url;359360 // Relative361 if (!~url.indexOf('://')) {362 // Respect mount-point

misc refactorTj Holowaychukbefore adoption490584c

line 363why, one step back
363 if (app.route) url = join(app.route, url);

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 364–366why, one step back
364
365 // Absolute366 var host = req.headers.host

refactored res.redirect()Tj Holowaychukbefore adoption9c9e2af

line 367why, one step back
367 , tls = req.connection.encrypted;

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 368–404why, one step back
368 url = 'http' + (tls ? 's' : '') + '://' + host + url;
369 }370 371372 // Support text/{plain,html} by default373 if (req.accepts('html')) {374 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';375 this.header('Content-Type', 'text/html');376 } else {377 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;378 this.header('Content-Type', 'text/plain');379 }380381 // Respond382 this.statusCode = status;383 this.header('Location', url);384 this.end(body);385};386387/**388 * Assign the view local variable `name` to `val` or return the389 * local previously assigned to `name`.390 *391 * @param {String} name392 * @param {Mixed} val393 * @return {Mixed} val394 * @api public395 */396397res.local = function(name, val){398 this._locals = this._locals || {};399 return undefined === val400 ? this._locals[name]401 : this._locals[name] = val;402};403404/**

Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64

lines 405–406why, one step back
405 * Assign several locals with the given `obj`,
406 * or return the locals.

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 407–408why, one step back
407 *
408 * @param {Object} obj

Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64

line 409why, one step back
409 * @return {Object|Undefined}

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

lines 410–412why, one step back
410 * @api public
411 */412

Added res.helpers() as alias of res.locals()Tj Holowaychukbefore adoptione4c840f

lines 413–414why, one step back
413res.locals =
414res.helpers = function(obj){

Changed; res.locals() without object returns the localsTj Holowaychukbefore adoptiona254e64

lines 415–421why, one step back
415 if (obj) {
416 for (var key in obj) {417 this.local(key, obj[key]);418 }419 } else {420 return this._locals;421 }

Fixed partials exampleTj Holowaychukbefore adoptiond5b7a40

line 422why, one step back
422};