Skip to content
Myr

response.js

This file

Path

lib/response.js

415 lines · 9.8 KiB · JavaScript

Last changed by

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

History of this file

Take it

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

miscTj Holowaychukbefore adoption0704f14

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

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 20why, one step back
20 , join = require('path').join

miscTj Holowaychukbefore adoption0704f14

lines 21–43why, one step back
21 , mime = require('mime');
2223/**24 * Send a response with the given `body` and optional `headers` and `status` code.25 *26 * Examples:27 *28 * res.send();29 * res.send(new Buffer('wahoo'));30 * res.send({ some: 'json' });31 * res.send('<p>some html</p>');32 * res.send('Sorry, cant find that', 404);33 * res.send('text', { 'Content-Type': 'text/plain' }, 201);34 * res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){

refactored res.send()Tj Holowaychukbefore adoption3661922

line 44why, one step back
44 // allow status as second arg

miscTj Holowaychukbefore adoption0704f14

lines 45–49why, one step back
45 if ('number' == typeof headers) {
46 status = headers,47 headers = null;48 }49

refactored res.send()Tj Holowaychukbefore adoption3661922

lines 50–51why, one step back
50 // default status
51 status = status || this.statusCode;

miscTj Holowaychukbefore adoption0704f14

line 52why, one step back
52

refactored res.send()Tj Holowaychukbefore adoption3661922

line 53why, one step back
53 // allow 0 args as 204

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

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

miscTj Holowaychukbefore adoption0704f14

line 55why, one step back
55

refactored res.send()Tj Holowaychukbefore adoption3661922

line 56why, one step back
56 // determine content type

miscTj Holowaychukbefore adoption0704f14

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

Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP]Tj Holowaychukbefore adoption3a1fe1e

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

miscTj Holowaychukbefore adoption0704f14

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

Added res.send(bool) supportTj Holowaychukbefore adoptionb7232f3

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

miscTj Holowaychukbefore adoption0704f14

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

Fixed SlowBuffer support. Closes #584Tj Holowaychukbefore adoption5da0163

line 72why, one step back
72 if (Buffer.isBuffer(body)) {

miscTj Holowaychukbefore adoption0704f14

lines 73–88why, one step back
73 if (!this.header('Content-Type')) {
74 this.contentType('.bin');75 }76 } else {77 if (!this.header('Content-Type')) {78 this.contentType('.json');79 }80 body = JSON.stringify(body);81 if (this.req.query.callback && this.app.set('jsonp callback')) {82 this.header('Content-Type', 'text/javascript');83 body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';84 }85 }86 break;87 }88

refactored res.send()Tj Holowaychukbefore adoption3661922

line 89why, one step back
89 // populate Content-Length

miscTj Holowaychukbefore adoption0704f14

line 90why, one step back
90 if (!this.header('Content-Length')) {

typoTj Holowaychukbefore adoption4874404

line 91why, one step back
91 this.header('Content-Length', Buffer.isBuffer(body)

miscTj Holowaychukbefore adoption0704f14

lines 92–95why, one step back
92 ? body.length
93 : Buffer.byteLength(body));94 }95

refactored res.send()Tj Holowaychukbefore adoption3661922

line 96why, one step back
96 // merge headers passed

miscTj Holowaychukbefore adoption0704f14

lines 97–104why, one step back
97 if (headers) {
98 var fields = Object.keys(headers);99 for (var i = 0, len = fields.length; i < len; ++i) {100 var field = fields[i];101 this.header(field, headers[field]);102 }103 }104

refactored res.send()Tj Holowaychukbefore adoption3661922

line 105why, one step back
105 // strip irrelevant headers

miscTj Holowaychukbefore adoption0704f14

lines 106–110why, one step back
106 if (204 === status) {
107 this.removeHeader('Content-Type');108 this.removeHeader('Content-Length');109 }110

refactored res.send()Tj Holowaychukbefore adoption3661922

lines 111–112why, one step back
111 // respond
112 this.statusCode = status;

miscTj Holowaychukbefore adoption0704f14

lines 113–132why, one step back
113 this.end('HEAD' == this.req.method ? undefined : body);
114};115116/**117 * Transfer the file at the given `path`. Automatically sets 118 * the _Content-Type_ response header field. `next()` is called119 * when `path` is a directory, or when an error occurs.120 *121 * Options:122 *123 * - `maxAge` defaulting to 0124 * - `root` root directory for relative filenames125 *126 * @param {String} path127 * @param {Object|Function} options or fn128 * @param {Function} fn129 * @api public130 */131132res.sendfile = function(path, options, fn){

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

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

miscTj Holowaychukbefore adoption0704f14

lines 134–143why, one step back
134 options = options || {};
135136 // support function as second arg137 if ('function' == typeof options) {138 fn = options;139 options = {};140 }141142 options.path = path;143 options.callback = fn;

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

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

miscTj Holowaychukbefore adoption0704f14

lines 145–186why, one step back
145};
146147/**148 * Set _Content-Type_ response header passed through `mime.lookup()`.149 *150 * Examples:151 *152 * var filename = 'path/to/image.png';153 * res.contentType(filename);154 * // res.headers['Content-Type'] is now "image/png"155 *156 * res.contentType('.html');157 * res.contentType('html');158 * res.contentType('json');159 * res.contentType('png');160 *161 * @param {String} type162 * @return {String} the resolved mime type163 * @api public164 */165166res.contentType = function(type){167 return this.header('Content-Type', mime.lookup(type));168};169170/**171 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.172 *173 * @param {String} filename174 * @return {ServerResponse}175 * @api public176 */177178res.attachment = function(filename){179 this.header('Content-Disposition', filename180 ? 'attachment; filename="' + path.basename(filename) + '"'181 : 'attachment');182 return this;183};184185/**186 * Transfer the file at the given `path`, with optional

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

lines 187–189why, one step back
187 * `filename` as an attachment and optional callback `fn(err)`,
188 * and optional `fn2(err)` which is invoked when an error has189 * occurred after headers have been sent.

miscTj Holowaychukbefore adoption0704f14

lines 190–193why, one step back
190 *
191 * @param {String} path192 * @param {String|Function} filename or fn193 * @param {Function} fn

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

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

miscTj Holowaychukbefore adoption0704f14

lines 195–197why, one step back
195 * @api public
196 */197

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

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

miscTj Holowaychukbefore adoption0704f14

lines 199–202why, one step back
199 var self = this;
200201 // support callback as second arg202 if ('function' == typeof filename) {

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

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

miscTj Holowaychukbefore adoption0704f14

lines 204–209why, one step back
204 fn = filename;
205 filename = null;206 }207208 // transfer the file209 this.attachment(filename || path).sendfile(path, function(err){

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

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

miscTj Holowaychukbefore adoption0704f14

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

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

lines 212–221why, one step back
212 if (!sentHeader) self.removeHeader('Content-Disposition');
213 if (sentHeader) {214 if (fn2) fn2(err);215 } else if (fn) {216 fn(err);217 } else {218 self.req.next(err);219 }220 } else if (fn) {221 fn();

miscTj Holowaychukbefore adoption0704f14

lines 222–255why, one step back
222 }
223 });224};225226/**227 * Set or get response header `name` with optional `val`.228 *229 * @param {String} name230 * @param {String} val231 * @return {String}232 * @api public233 */234235res.header = function(name, val){236 if (val === undefined) {237 return this.getHeader(name);238 } else {239 this.setHeader(name, val);240 return val;241 }242};243244/**245 * Clear cookie `name`.246 *247 * @param {String} name248 * @api public249 */250251res.clearCookie = function(name){252 this.cookie(name, '', { expires: new Date(1) });253};254255/**

Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5

line 256why, one step back
256 * Set cookie `name` to `val`, with the given `options`.

miscTj Holowaychukbefore adoption0704f14

line 257why, one step back
257 *

Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5

lines 258–261why, one step back
258 * Options:
259 *260 * - `maxAge` max-age in milliseconds, converted to `expires`261 *

miscTj Holowaychukbefore adoption0704f14

lines 262–266why, one step back
262 * Examples:
263 *264 * // "Remember Me" for 15 minutes265 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });266 *

Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5

lines 267–269why, one step back
267 * // save as above
268 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })269 *

miscTj Holowaychukbefore adoption0704f14

lines 270–276why, one step back
270 * @param {String} name
271 * @param {String} val272 * @param {Options} options273 * @api public274 */275276res.cookie = function(name, val, options){

Added res.cookie() maxAge supportTj Holowaychukbefore adoption4c274c5

lines 277–278why, one step back
277 options = options || {};
278 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);

miscTj Holowaychukbefore adoption0704f14

lines 279–318why, one step back
279 var cookie = utils.serializeCookie(name, val, options);
280 this.header('Set-Cookie', cookie);281};282283/**284 * Redirect to the given `url` with optional response `status`285 * defauling to 302.286 *287 * The given `url` can also be the name of a mapped url, for288 * example by default express supports "back" which redirects289 * to the _Referrer_ or _Referer_ headers or the application's290 * "home" setting. Express also supports "home" out of the box,291 * which can be set via `app.set('home', '/blog');`, and defaults292 * to '/'.293 *294 * Redirect Mapping:295 * 296 * To extend the redirect mapping capabilities that Express provides,297 * we may use the `app.redirect()` method:298 * 299 * app.redirect('google', 'http://google.com');300 * 301 * Now in a route we may call:302 *303 * res.redirect('google');304 *305 * We may also map dynamic redirects:306 *307 * app.redirect('comments', function(req, res){308 * return '/post/' + req.params.id + '/comments';309 * });310 *311 * So now we may do the following, and the redirect will dynamically adjust to312 * the context of the request. If we called this route with _GET /post/12_ our313 * redirect _Location_ would be _/post/12/comments_.314 *315 * app.get('/post/:id', function(req, res){316 * res.redirect('comments');317 * });318 *

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

lines 319–322why, one step back
319 * Unless an absolute `url` is given, the app's mount-point
320 * will be respected. For example if we redirect to `/posts`,321 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.322 *

miscTj Holowaychukbefore adoption0704f14

lines 323–328why, one step back
323 * @param {String} url
324 * @param {Number} code325 * @api public326 */327328res.redirect = function(url, status){

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 329why, one step back
329 var app = this.app

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 330why, one step back
330 , req = this.req

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 331why, one step back
331 , base = app.set('home') || '/'

miscTj Holowaychukbefore adoption0704f14

lines 332–336why, one step back
332 , status = status || 302
333 , body;334335 // Setup redirect map336 var map = {

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 337why, one step back
337 back: req.header('Referrer', base)

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 338why, one step back
338 , home: base

miscTj Holowaychukbefore adoption0704f14

lines 339–341why, one step back
339 };
340341 // Support custom redirect map

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 342why, one step back
342 map.__proto__ = app.redirects;

miscTj Holowaychukbefore adoption0704f14

lines 343–344why, one step back
343
344 // Attempt mapped redirect

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 345why, one step back
345 var mapped = 'function' == typeof map[url]

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 346why, one step back
346 ? map[url](req, this)

miscTj Holowaychukbefore adoption0704f14

lines 347–350why, one step back
347 : map[url];
348349 // Perform redirect350 url = mapped || url;

Merge branch 'mounting'Tj Holowaychukbefore adoptiona572a71

line 351why, one step back
351

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 352–357why, one step back
352 // Relative
353 if (!~url.indexOf('://')) {354 // Respect mount-point355 if (app.route) {356 url = join(app.route, url);357 }

miscTj Holowaychukbefore adoption0704f14

line 358why, one step back
358

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 359–360why, one step back
359 // Absolute
360 var host = req.headers.host

refactored res.redirect()Tj Holowaychukbefore adoption9c9e2af

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

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

lines 362–365why, one step back
362 url = 'http' + (tls ? 's' : '') + '://' + host + url;
363 }364 365

miscTj Holowaychukbefore adoption0704f14

line 366why, one step back
366 // Support text/{plain,html} by default

Fixed res.redirect(). RFC states absoluteTj Holowaychukbefore adoptionc92e193

line 367why, one step back
367 if (req.accepts('html')) {

miscTj Holowaychukbefore adoption0704f14

lines 368–375why, one step back
368 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';
369 this.header('Content-Type', 'text/html');370 } else {371 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;372 this.header('Content-Type', 'text/plain');373 }374375 // Respond

Added res.redirect() mount testTj Holowaychukbefore adoption99dcf75

lines 376–378why, one step back
376 this.statusCode = status;
377 this.header('Location', url);378 this.end(body);

miscTj Holowaychukbefore adoption0704f14

lines 379–391why, one step back
379};
380381/**382 * Assign the view local variable `name` to `val` or return the383 * local previously assigned to `name`.384 *385 * @param {String} name386 * @param {Mixed} val387 * @return {Mixed} val388 * @api public389 */390391res.local = function(name, val){

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

line 392why, one step back
392 this._locals = this._locals || {};

miscTj Holowaychukbefore adoption0704f14

line 393why, one step back
393 return undefined === val

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 394–398why, one step back
394 ? this._locals[name]
395 : this._locals[name] = val;396};397398/**

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

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

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 401–402why, one step back
401 *
402 * @param {Object} obj

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

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

Added res.locals(obj)Tj Holowaychukbefore adoption0b1378a

lines 404–407why, one step back
404 * @api public
405 */406407res.locals = function(obj){

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

lines 408–414why, one step back
408 if (obj) {
409 for (var key in obj) {410 this.local(key, obj[key]);411 }412 } else {413 return this._locals;414 }

miscTj Holowaychukbefore adoption0704f14

line 415why, one step back
415};