response.js
This file
Path
lib/response.js
471 lines · 11.2 KiB · JavaScript
Last changed by
Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
History of this fileTake it
The walk stopped after 200 commits: lines older than 0c38098 point at it.
tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 1–19why, one step back12/*!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.sendmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 20–22why, one step back20 , mime = require('mime')21 , basename = path.basename22 , join = path.join;tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 23–54why, one step back2324/**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 204res.send(undefined) returns a 204Aaron Heckmannbefore adoption673ba22
line 55why, one step back55 if (!arguments.length || undefined === body) body = status = 204;tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 56–66why, one step back5657 // 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 back67 this.charset = this.charset || 'utf-8';tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 68–78why, one step back68 this.contentType('.html');69 }70 break;71 case 'boolean':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 back79 this.charset = this.charset || 'utf-8';tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 80–83why, one step back80 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 back84 this.charset = this.charset || 'utf-8';tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 85–108why, one step back85 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 headersFixed; ignore body on 304. Closes #701Tj Holowaychukbefore adoption9028cac
line 109why, one step back109 if (204 == status || 304 == status) {tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 110–116why, one step back110 this.removeHeader('Content-Type');111 this.removeHeader('Content-Length');112 }113114 // respond115 this.statusCode = status;116 this.end('HEAD' == this.req.method ? undefined : body);Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 117–137why, one step back117 return this;118};119120/**121 * Send JSON response with `obj`, optional `headers`, and optional `status`.122 *123 * Examples:124 *125 * res.json(null);126 * res.json({ user: 'tj' });127 * res.json('oh noes!', 500);128 * res.json('I dont have that', 404);129 *130 * @param {Mixed} obj131 * @param {Object|Number} headers or status132 * @param {Number} status133 * @return {ServerResponse}134 * @api public135 */136137res.json = function(obj, headers, status){Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 138–141why, one step back138 var body = JSON.stringify(obj)139 , callback = this.req.query.callback140 , jsonp = this.app.enabled('jsonp callback');141Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 142–143why, one step back142 this.charset = this.charset || 'utf-8';143 this.header('Content-Type', 'application/json');Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 144–150why, one step back144145 if (callback && jsonp) {146 this.header('Content-Type', 'text/javascript');147 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';148 }149150 return this.send(body, headers, status);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 151–152why, one step back151};152docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 153–160why, one step back153/**154 * Set status `code`.155 *156 * @param {Number} code157 * @return {ServerResponse}158 * @api public159 */160Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51
lines 161–165why, one step back161res.status = function(code){162 this.statusCode = code;163 return this;164};165tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 166–182why, one step back166/**167 * Transfer the file at the given `path`. Automatically sets 168 * the _Content-Type_ response header field. `next()` is called169 * when `path` is a directory, or when an error occurs.170 *171 * Options:172 *173 * - `maxAge` defaulting to 0174 * - `root` root directory for relative filenames175 *176 * @param {String} path177 * @param {Object|Function} options or fn178 * @param {Function} fn179 * @api public180 */181182res.sendfile = function(path, options, fn){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 183why, one step back183 var next = this.req.next;tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 184–191why, one step back184 options = options || {};185186 // support function as second arg187 if ('function' == typeof options) {188 fn = options;189 options = {};190 }191Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608
line 192why, one step back192 options.path = encodeURIComponent(path);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
line 193why, one step back193 options.callback = fn;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 194why, one step back194 send(this.req, this, next, options);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 195–228why, one step back195};196197/**198 * Set _Content-Type_ response header passed through `mime.lookup()`.199 *200 * Examples:201 *202 * var filename = 'path/to/image.png';203 * res.contentType(filename);204 * // res.headers['Content-Type'] is now "image/png"205 *206 * res.contentType('.html');207 * res.contentType('html');208 * res.contentType('json');209 * res.contentType('png');210 *211 * @param {String} type212 * @return {String} the resolved mime type213 * @api public214 */215216res.contentType = function(type){217 return this.header('Content-Type', mime.lookup(type));218};219220/**221 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.222 *223 * @param {String} filename224 * @return {ServerResponse}225 * @api public226 */227228res.attachment = function(filename){auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
line 229why, one step back229 if (filename) this.contentType(filename);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
line 230why, one step back230 this.header('Content-Disposition', filenamemisc refactoringTj Holowaychukbefore adoption70e6baf
line 231why, one step back231 ? 'attachment; filename="' + basename(filename) + '"'tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 232–237why, one step back232 : 'attachment');233 return this;234};235236/**237 * Transfer the file at the given `path`, with optional Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 238–239why, one step back238 * `filename` as an attachment and optional callback `fn(err)`,239 * and optional `fn2(err)` which is invoked when an error hastypoTj Holowaychukbefore adoption0cbb1f6
line 240why, one step back240 * occurred after header has been sent.tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 241–244why, one step back241 *242 * @param {String} path243 * @param {String|Function} filename or fn244 * @param {Function} fnAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 245why, one step back245 * @param {Function} fn2tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 246–248why, one step back246 * @api public247 */248Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 249why, one step back249res.download = function(path, filename, fn, fn2){tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 250–253why, one step back250 var self = this;251252 // support callback as second arg253 if ('function' == typeof filename) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 254why, one step back254 fn2 = fn;tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 255–260why, one step back255 fn = filename;256 filename = null;257 }258259 // transfer the file260 this.attachment(filename || path).sendfile(path, function(err){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 261why, one step back261 var sentHeader = self._header;tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
line 262why, one step back262 if (err) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 263–264why, one step back263 if (!sentHeader) self.removeHeader('Content-Disposition');264 if (sentHeader) {misc refactorTj Holowaychukbefore adoptionaa68581
line 265why, one step back265 fn2 && fn2(err);Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 266–272why, one step back266 } else if (fn) {267 fn(err);268 } else {269 self.req.next(err);270 }271 } else if (fn) {272 fn();tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 273–298why, one step back273 }274 });275};276277/**278 * Set or get response header `name` with optional `val`.279 *280 * @param {String} name281 * @param {String} val282 * @return {String}283 * @api public284 */285286res.header = function(name, val){287 if (val === undefined) {288 return this.getHeader(name);289 } else {290 this.setHeader(name, val);291 return val;292 }293};294295/**296 * Clear cookie `name`.297 *298 * @param {String} nameAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 299why, one step back299 * @param {Object} optionstweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 300–302why, one step back300 * @api public301 */302Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 303–307why, one step back303res.clearCookie = function(name, options){304 var opts = { expires: new Date(1) };305 this.cookie(name, '', options306 ? utils.merge(options, opts)307 : opts);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 308–315why, one step back308};309310/**311 * Set cookie `name` to `val`, with the given `options`.312 *313 * Options:314 *315 * - `maxAge` max-age in milliseconds, converted to `expires`Changed; default cookie path to "home" setting. Closes #731Tj Holowaychukbefore adoption09c9452
line 316why, one step back316 * - `path` defaults to the "home" setting which is typically "/"tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 317–334why, one step back317 *318 * Examples:319 *320 * // "Remember Me" for 15 minutes321 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });322 *323 * // save as above324 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })325 *326 * @param {String} name327 * @param {String} val328 * @param {Options} options329 * @api public330 */331332res.cookie = function(name, val, options){333 options = options || {};334 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b
line 335why, one step back335 if (undefined === options.path) options.path = this.app.set('home');tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 336–411why, one step back336 var cookie = utils.serializeCookie(name, val, options);337 this.header('Set-Cookie', cookie);338};339340/**341 * Redirect to the given `url` with optional response `status`342 * defauling to 302.343 *344 * The given `url` can also be the name of a mapped url, for345 * example by default express supports "back" which redirects346 * to the _Referrer_ or _Referer_ headers or the application's347 * "home" setting. Express also supports "home" out of the box,348 * which can be set via `app.set('home', '/blog');`, and defaults349 * to '/'.350 *351 * Redirect Mapping:352 * 353 * To extend the redirect mapping capabilities that Express provides,354 * we may use the `app.redirect()` method:355 * 356 * app.redirect('google', 'http://google.com');357 * 358 * Now in a route we may call:359 *360 * res.redirect('google');361 *362 * We may also map dynamic redirects:363 *364 * app.redirect('comments', function(req, res){365 * return '/post/' + req.params.id + '/comments';366 * });367 *368 * So now we may do the following, and the redirect will dynamically adjust to369 * the context of the request. If we called this route with _GET /post/12_ our370 * redirect _Location_ would be _/post/12/comments_.371 *372 * app.get('/post/:id', function(req, res){373 * res.redirect('comments');374 * });375 *376 * Unless an absolute `url` is given, the app's mount-point377 * will be respected. For example if we redirect to `/posts`,378 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.379 *380 * @param {String} url381 * @param {Number} code382 * @api public383 */384385res.redirect = function(url, status){386 var app = this.app387 , req = this.req388 , base = app.set('home') || '/'389 , status = status || 302390 , body;391392 // Setup redirect map393 var map = {394 back: req.header('Referrer', base)395 , home: base396 };397398 // Support custom redirect map399 map.__proto__ = app.redirects;400401 // Attempt mapped redirect402 var mapped = 'function' == typeof map[url]403 ? map[url](req, this)404 : map[url];405406 // Perform redirect407 url = mapped || url;408409 // Relative410 if (!~url.indexOf('://')) {411 // Respect mount-pointmisc refactorTj Holowaychukbefore adoption490584c
line 412why, one step back412 if (app.route) url = join(app.route, url);tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 413–461why, one step back413414 // Absolute415 var host = req.headers.host416 , tls = req.connection.encrypted;417 url = 'http' + (tls ? 's' : '') + '://' + host + url;418 }419 420421 // Support text/{plain,html} by default422 if (req.accepts('html')) {423 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';424 this.header('Content-Type', 'text/html');425 } else {426 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;427 this.header('Content-Type', 'text/plain');428 }429430 // Respond431 this.statusCode = status;432 this.header('Location', url);433 this.end(body);434};435436/**437 * Assign the view local variable `name` to `val` or return the438 * local previously assigned to `name`.439 *440 * @param {String} name441 * @param {Mixed} val442 * @return {Mixed} val443 * @api public444 */445446res.local = function(name, val){447 this._locals = this._locals || {};448 return undefined === val449 ? this._locals[name]450 : this._locals[name] = val;451};452453/**454 * Assign several locals with the given `obj`,455 * or return the locals.456 *457 * @param {Object} obj458 * @return {Object|Undefined}459 * @api public460 */461Added res.helpers() as alias of res.locals()Tj Holowaychukbefore adoptione4c840f
lines 462–463why, one step back462res.locals =463res.helpers = function(obj){tweak req.flash() failure messageTj Holowaychukbefore adoption0c38098
lines 464–471why, one step back464 if (obj) {465 for (var key in obj) {466 this.local(key, obj[key]);467 }468 } else {469 return this._locals;470 }471};