response.js
This file
Path
lib/response.js
922 lines · 20.9 KiB · JavaScript
Last changed by
Merge tag '4.11.2'Douglas Christopher Wilsonbefore adoptiona9ef9e1
History of this fileTake it
The walk stopped after 200 commits: lines older than 4279e6e point at it.
improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 1–4why, one step back1/**2 * Module dependencies.3 */4Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 5why, one step back5var contentDisposition = require('content-disposition');Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff
line 6why, one step back6var deprecate = require('depd')('express');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 7–8why, one step back7var escapeHtml = require('escape-html');8var http = require('http');Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 9why, one step back9var isAbsolute = require('./utils').isAbsolute;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 10why, one step back10var onFinished = require('on-finished');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 11why, one step back11var path = require('path');Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 12why, one step back12var merge = require('utils-merge');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 13–21why, one step back13var sign = require('cookie-signature').sign;14var normalizeType = require('./utils').normalizeType;15var normalizeTypes = require('./utils').normalizeTypes;16var setCharset = require('./utils').setCharset;17var statusCodes = http.STATUS_CODES;18var cookie = require('cookie');19var send = require('send');20var extname = path.extname;21var mime = send.mime;Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 22why, one step back22var resolve = path.resolve;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 23–77why, one step back23var vary = require('vary');2425/**26 * Response prototype.27 */2829var res = module.exports = {30 __proto__: http.ServerResponse.prototype31};3233/**34 * Set status `code`.35 *36 * @param {Number} code37 * @return {ServerResponse}38 * @api public39 */4041res.status = function(code){42 this.statusCode = code;43 return this;44};4546/**47 * Set Link header field with the given `links`.48 *49 * Examples:50 *51 * res.links({52 * next: 'http://api.example.com/users?page=2',53 * last: 'http://api.example.com/users?page=5'54 * });55 *56 * @param {Object} links57 * @return {ServerResponse}58 * @api public59 */6061res.links = function(links){62 var link = this.get('Link') || '';63 if (link) link += ', ';64 return this.set('Link', link + Object.keys(links).map(function(rel){65 return '<' + links[rel] + '>; rel="' + rel + '"';66 }).join(', '));67};6869/**70 * Send a response.71 *72 * Examples:73 *74 * res.send(new Buffer('wahoo'));75 * res.send({ some: 'json' });76 * res.send('<p>some html</p>');77 *Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 78why, one step back78 * @param {string|number|boolean|object|Buffer} bodyimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 79–81why, one step back79 * @api public80 */81perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 82–83why, one step back82res.send = function send(body) {83 var chunk = body;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 84–85why, one step back84 var encoding;85 var len;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 86–87why, one step back86 var req = this.req;87 var type;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 88–91why, one step back8889 // settings90 var app = this.app;91Remove res.send(body, status) signatureDouglas Christopher Wilsonbefore adoptione66625b
line 92why, one step back92 // support res.send(status, body)perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 93why, one step back93 if (arguments.length === 2) {Remove res.send(body, status) signatureDouglas Christopher Wilsonbefore adoptione66625b
lines 94–96why, one step back94 deprecate('res.send(status, body): Use res.status(status).send(body) instead');95 this.statusCode = arguments[0];96 chunk = arguments[1];improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 97–98why, one step back97 }98perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 99why, one step back99 switch (typeof chunk) {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 100–101why, one step back100 // string defaulting to html101 case 'string':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 102–104why, one step back102 if (!this.get('Content-Type')) {103 this.type('html');104 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 105–106why, one step back105 break;106 case 'boolean':Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
line 107why, one step back107 case 'number':improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 108why, one step back108 case 'object':perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 109–114why, one step back109 if (chunk === null) {110 chunk = '';111 } else if (Buffer.isBuffer(chunk)) {112 if (!this.get('Content-Type')) {113 this.type('bin');114 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 115why, one step back115 } else {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 116why, one step back116 return this.json(chunk);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 117–121why, one step back117 }118 break;119 }120121 // write strings in utf-8perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 122why, one step back122 if (typeof chunk === 'string') {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 123–126why, one step back123 encoding = 'utf8';124 type = this.get('Content-Type');125126 // reflect this in content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 127why, one step back127 if (typeof type === 'string') {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 128–132why, one step back128 this.set('Content-Type', setCharset(type, 'utf-8'));129 }130 }131132 // populate Content-Lengthperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 133–140why, one step back133 if (chunk !== undefined) {134 if (!Buffer.isBuffer(chunk)) {135 // convert chunk to Buffer; saves later double conversions136 chunk = new Buffer(chunk, encoding);137 encoding = undefined;138 }139140 len = chunk.length;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 141–143why, one step back141 this.set('Content-Length', len);142 }143perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 144–146why, one step back144 // method check145 var isHead = req.method === 'HEAD';146improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 147why, one step back147 // ETag supportperf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
lines 148–150why, one step back148 if (len !== undefined && (isHead || req.method === 'GET')) {149 var etag = app.get('etag fn');150 if (etag && !this.get('ETag')) {perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 151why, one step back151 etag = etag(chunk, encoding);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 152–163why, one step back152 etag && this.set('ETag', etag);153 }154 }155156 // freshness157 if (req.fresh) this.statusCode = 304;158159 // strip irrelevant headers160 if (204 == this.statusCode || 304 == this.statusCode) {161 this.removeHeader('Content-Type');162 this.removeHeader('Content-Length');163 this.removeHeader('Transfer-Encoding');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 164why, one step back164 chunk = '';improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 165–166why, one step back165 }166perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c
line 167why, one step back167 if (isHead) {Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
line 168why, one step back168 // skip body for HEADperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 169why, one step back169 this.end();Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 170–172why, one step back170 } else {171 // respond172 this.end(chunk, encoding);perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 173–174why, one step back173 }174improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 175–185why, one step back175 return this;176};177178/**179 * Send JSON response.180 *181 * Examples:182 *183 * res.json(null);184 * res.json({ user: 'tj' });185 *Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 186why, one step back186 * @param {string|number|boolean|object} objimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 187–189why, one step back187 * @api public188 */189perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 190–192why, one step back190res.json = function json(obj) {191 var val = obj;192Remove res.json(obj, status) signatureDouglas Christopher Wilsonbefore adoption164638b
line 193why, one step back193 // support res.json(status, obj)perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 194why, one step back194 if (arguments.length === 2) {Remove res.json(obj, status) signatureDouglas Christopher Wilsonbefore adoption164638b
lines 195–197why, one step back195 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');196 this.statusCode = arguments[0];197 val = arguments[1];improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 198–203why, one step back198 }199200 // settings201 var app = this.app;202 var replacer = app.get('json replacer');203 var spaces = app.get('json spaces');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 204why, one step back204 var body = JSON.stringify(val, replacer, spaces);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 205–206why, one step back205206 // content-typeperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 207–209why, one step back207 if (!this.get('Content-Type')) {208 this.set('Content-Type', 'application/json');209 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 210–221why, one step back210211 return this.send(body);212};213214/**215 * Send JSON response with JSONP callback support.216 *217 * Examples:218 *219 * res.jsonp(null);220 * res.jsonp({ user: 'tj' });221 *Deprecate combined status, response signaturesDouglas Christopher Wilsonbefore adoptionfd3b405
line 222why, one step back222 * @param {string|number|boolean|object} objimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 223–225why, one step back223 * @api public224 */225perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 226–228why, one step back226res.jsonp = function jsonp(obj) {227 var val = obj;228Remove res.jsonp(obj, status) signatureDouglas Christopher Wilsonbefore adoption8810306
line 229why, one step back229 // support res.jsonp(status, obj)perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 230why, one step back230 if (arguments.length === 2) {Remove res.jsonp(obj, status) signatureDouglas Christopher Wilsonbefore adoption8810306
lines 231–233why, one step back231 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');232 this.statusCode = arguments[0];233 val = arguments[1];improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 234–239why, one step back234 }235236 // settings237 var app = this.app;238 var replacer = app.get('json replacer');239 var spaces = app.get('json spaces');perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 240why, one step back240 var body = JSON.stringify(val, replacer, spaces);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 241–243why, one step back241 var callback = this.req.query[app.get('jsonp callback name')];242243 // content-typeMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 244–247why, one step back244 if (!this.get('Content-Type')) {245 this.set('X-Content-Type-Options', 'nosniff');246 this.set('Content-Type', 'application/json');247 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 248–254why, one step back248249 // fixup callback250 if (Array.isArray(callback)) {251 callback = callback[0];252 }253254 // jsonpMerge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 255–257why, one step back255 if (typeof callback === 'string' && callback.length !== 0) {256 this.charset = 'utf-8';257 this.set('X-Content-Type-Options', 'nosniff');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 258why, one step back258 this.set('Content-Type', 'text/javascript');Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21
lines 259–270why, one step back259260 // restrict callback charset261 callback = callback.replace(/[^\[\]\w$.]/g, '');262263 // replace chars not allowed in JavaScript that are in JSON264 body = body265 .replace(/\u2028/g, '\\u2028')266 .replace(/\u2029/g, '\\u2029');267268 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"269 // the typeof check is just to reduce client error noise270 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 271–273why, one step back271 }272273 return this.send(body);Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 274–276why, one step back274};275276/**Add res.sendStatusSeth Samuelbefore adoption12f92a5
lines 277–300why, one step back277 * Send given HTTP status code.278 *279 * Sets the response status to `statusCode` and the body of the280 * response to the standard description from node's http.STATUS_CODES281 * or the statusCode number if no description.282 *283 * Examples:284 *285 * res.sendStatus(200);286 *287 * @param {number} statusCode288 * @api public289 */290291res.sendStatus = function sendStatus(statusCode) {292 var body = http.STATUS_CODES[statusCode] || String(statusCode);293294 this.statusCode = statusCode;295 this.type('txt');296297 return this.send(body);298};299300/**Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 301–342why, one step back301 * Transfer the file at the given `path`.302 *303 * Automatically sets the _Content-Type_ response header field.304 * The callback `fn(err)` is invoked when the transfer is complete305 * or when an error occurs. Be sure to check `res.sentHeader`306 * if you wish to attempt responding, as the header and some data307 * may have already been transferred.308 *309 * Options:310 *311 * - `maxAge` defaulting to 0 (can be string converted by `ms`)312 * - `root` root directory for relative filenames313 * - `headers` object of headers to serve with file314 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them315 *316 * Other options are passed along to `send`.317 *318 * Examples:319 *320 * The following example illustrates how `res.sendFile()` may321 * be used as an alternative for the `static()` middleware for322 * dynamic situations. The code backing `res.sendFile()` is actually323 * the same code, so HTTP cache support etc is identical.324 *325 * app.get('/user/:uid/photos/:file', function(req, res){326 * var uid = req.params.uid327 * , file = req.params.file;328 *329 * req.user.mayViewFilesFrom(uid, function(yes){330 * if (yes) {331 * res.sendFile('/uploads/' + uid + '/' + file);332 * } else {333 * res.send(403, 'Sorry! you cant see that.');334 * }335 * });336 * });337 *338 * @api public339 */340341res.sendFile = function sendFile(path, options, fn) {342 var req = this.req;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 343why, one step back343 var res = this;Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 344–361why, one step back344 var next = req.next;345346 if (!path) {347 throw new TypeError('path argument is required to res.sendFile');348 }349350 // support function as second arg351 if (typeof options === 'function') {352 fn = options;353 options = {};354 }355356 options = options || {};357358 if (!options.root && !isAbsolute(path)) {359 throw new TypeError('path must be absolute or specify root to res.sendFile');360 }361Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 362why, one step back362 // create file streamAdd res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
lines 363–365why, one step back363 var pathname = encodeURI(path);364 var file = send(req, pathname, options);365Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 366–369why, one step back366 // transfer367 sendfile(res, file, options, function (err) {368 if (fn) return fn(err);369 if (err && err.code === 'EISDIR') return next();Add res.sendFileDouglas Christopher Wilsonbefore adoption2cb029f
line 370why, one step back370Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 371–372why, one step back371 // next() all but write errors372 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 373–375why, one step back373 next(err);374 }375 });improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 376–385why, one step back376};377378/**379 * Transfer the file at the given `path` as an attachment.380 *381 * Optionally providing an alternate attachment `filename`,382 * and optional callback `fn(err)`. The callback is invoked383 * when the data transfer is complete, or when an error has384 * ocurred. Be sure to check `res.headersSent` if you plan to respond.385 *Remove res.sendfileDouglas Christopher Wilsonbefore adoption0fc4f07
line 386why, one step back386 * This method uses `res.sendFile()`.improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 387–390why, one step back387 *388 * @api public389 */390Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 391why, one step back391res.download = function download(path, filename, fn) {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 392why, one step back392 // support function as second argFix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
line 393why, one step back393 if (typeof filename === 'function') {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 394–398why, one step back394 fn = filename;395 filename = null;396 }397398 filename = filename || path;Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe
lines 399–404why, one step back399400 // set Content-Disposition when file is sent401 var headers = {402 'Content-Disposition': contentDisposition(filename)403 };404Fix incorrect deprecation warnings on res.downloadDouglas Christopher Wilsonbefore adoption1150ca7
lines 405–408why, one step back405 // Resolve the full path for sendFile406 var fullPath = resolve(path);407408 return this.sendFile(fullPath, { headers: headers }, fn);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 409–526why, one step back409};410411/**412 * Set _Content-Type_ response header with `type` through `mime.lookup()`413 * when it does not contain "/", or set the Content-Type to `type` otherwise.414 *415 * Examples:416 *417 * res.type('.html');418 * res.type('html');419 * res.type('json');420 * res.type('application/json');421 * res.type('png');422 *423 * @param {String} type424 * @return {ServerResponse} for chaining425 * @api public426 */427428res.contentType =429res.type = function(type){430 return this.set('Content-Type', ~type.indexOf('/')431 ? type432 : mime.lookup(type));433};434435/**436 * Respond to the Acceptable formats using an `obj`437 * of mime-type callbacks.438 *439 * This method uses `req.accepted`, an array of440 * acceptable types ordered by their quality values.441 * When "Accept" is not present the _first_ callback442 * is invoked, otherwise the first match is used. When443 * no match is performed the server responds with444 * 406 "Not Acceptable".445 *446 * Content-Type is set for you, however if you choose447 * you may alter this within the callback using `res.type()`448 * or `res.set('Content-Type', ...)`.449 *450 * res.format({451 * 'text/plain': function(){452 * res.send('hey');453 * },454 *455 * 'text/html': function(){456 * res.send('<p>hey</p>');457 * },458 *459 * 'appliation/json': function(){460 * res.send({ message: 'hey' });461 * }462 * });463 *464 * In addition to canonicalized MIME types you may465 * also use extnames mapped to these types:466 *467 * res.format({468 * text: function(){469 * res.send('hey');470 * },471 *472 * html: function(){473 * res.send('<p>hey</p>');474 * },475 *476 * json: function(){477 * res.send({ message: 'hey' });478 * }479 * });480 *481 * By default Express passes an `Error`482 * with a `.status` of 406 to `next(err)`483 * if a match is not made. If you provide484 * a `.default` callback it will be invoked485 * instead.486 *487 * @param {Object} obj488 * @return {ServerResponse} for chaining489 * @api public490 */491492res.format = function(obj){493 var req = this.req;494 var next = req.next;495496 var fn = obj.default;497 if (fn) delete obj.default;498 var keys = Object.keys(obj);499500 var key = req.accepts(keys);501502 this.vary("Accept");503504 if (key) {505 this.set('Content-Type', normalizeType(key).value);506 obj[key](req, this, next);507 } else if (fn) {508 fn();509 } else {510 var err = new Error('Not Acceptable');511 err.status = 406;512 err.types = normalizeTypes(keys).map(function(o){ return o.value });513 next(err);514 }515516 return this;517};518519/**520 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.521 *522 * @param {String} filename523 * @return {ServerResponse}524 * @api public525 */526Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
lines 527–531why, one step back527res.attachment = function attachment(filename) {528 if (filename) {529 this.type(extname(filename));530 }531improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 532why, one step back532 this.set('Content-Disposition', contentDisposition(filename));Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218
line 533why, one step back533improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 534–537why, one step back534 return this;535};536537/**Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 538–566why, one step back538 * Append additional header `field` with value `val`.539 *540 * Example:541 *542 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);543 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');544 * res.append('Warning', '199 Miscellaneous warning');545 *546 * @param {String} field547 * @param {String|Array} val548 * @return {ServerResponse} for chaining549 * @api public550 */551552res.append = function append(field, val) {553 var prev = this.get(field);554 var value = val;555556 if (prev) {557 // concat the new and prev vals558 value = Array.isArray(prev) ? prev.concat(val)559 : Array.isArray(val) ? [prev].concat(val)560 : [prev, val];561 }562563 return this.set(field, value);564};565566/**improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 567–584why, one step back567 * Set header `field` to `val`, or pass568 * an object of header fields.569 *570 * Examples:571 *572 * res.set('Foo', ['bar', 'baz']);573 * res.set('Accept', 'application/json');574 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });575 *576 * Aliased as `res.header()`.577 *578 * @param {String|Object|Array} field579 * @param {String} val580 * @return {ServerResponse} for chaining581 * @api public582 */583584res.set =perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 585–586why, one step back585res.header = function header(field, val) {586 if (arguments.length === 2) {improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 587–618why, one step back587 if (Array.isArray(val)) val = val.map(String);588 else val = String(val);589 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {590 var charset = mime.charsets.lookup(val.split(';')[0]);591 if (charset) val += '; charset=' + charset.toLowerCase();592 }593 this.setHeader(field, val);594 } else {595 for (var key in field) {596 this.set(key, field[key]);597 }598 }599 return this;600};601602/**603 * Get value for header `field`.604 *605 * @param {String} field606 * @return {String}607 * @api public608 */609610res.get = function(field){611 return this.getHeader(field);612};613614/**615 * Clear cookie `name`.616 *617 * @param {String} name618 * @param {Object} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 619why, one step back619 * @return {ServerResponse} for chainingimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 620–625why, one step back620 * @api public621 */622623res.clearCookie = function(name, options){624 var opts = { expires: new Date(1), path: '/' };625 return this.cookie(name, '', optionsMerge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 626why, one step back626 ? merge(opts, options)improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 627–649why, one step back627 : opts);628};629630/**631 * Set cookie `name` to `val`, with the given `options`.632 *633 * Options:634 *635 * - `maxAge` max-age in milliseconds, converted to `expires`636 * - `signed` sign the cookie637 * - `path` defaults to "/"638 *639 * Examples:640 *641 * // "Remember Me" for 15 minutes642 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });643 *644 * // save as above645 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })646 *647 * @param {String} name648 * @param {String|Object} val649 * @param {Options} optionsbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 650why, one step back650 * @return {ServerResponse} for chainingimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 651–654why, one step back651 * @api public652 */653654res.cookie = function(name, val, options){Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7
line 655why, one step back655 options = merge({}, options);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 656–695why, one step back656 var secret = this.req.secret;657 var signed = options.signed;658 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');659 if ('number' == typeof val) val = val.toString();660 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);661 if (signed) val = 's:' + sign(val, secret);662 if ('maxAge' in options) {663 options.expires = new Date(Date.now() + options.maxAge);664 options.maxAge /= 1000;665 }666 if (null == options.path) options.path = '/';667 var headerVal = cookie.serialize(name, String(val), options);668669 // supports multiple 'res.cookie' calls by getting previous value670 var prev = this.get('Set-Cookie');671 if (prev) {672 if (Array.isArray(prev)) {673 headerVal = prev.concat(headerVal);674 } else {675 headerVal = [prev, headerVal];676 }677 }678 this.set('Set-Cookie', headerVal);679 return this;680};681682683/**684 * Set the location header to `url`.685 *686 * The given `url` can also be "back", which redirects687 * to the _Referrer_ or _Referer_ headers or "/".688 *689 * Examples:690 *691 * res.location('/foo/bar').;692 * res.location('http://example.com');693 * res.location('../login');694 *695 * @param {String} urlbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 696why, one step back696 * @return {ServerResponse} for chainingimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 697–728why, one step back697 * @api public698 */699700res.location = function(url){701 var req = this.req;702703 // "back" is an alias for the referrer704 if ('back' == url) url = req.get('Referrer') || '/';705706 // Respond707 this.set('Location', url);708 return this;709};710711/**712 * Redirect to the given `url` with optional response `status`713 * defaulting to 302.714 *715 * The resulting `url` is determined by `res.location()`, so716 * it will play nicely with mounted apps, relative paths,717 * `"back"` etc.718 *719 * Examples:720 *721 * res.redirect('/foo/bar');722 * res.redirect('http://example.com');723 * res.redirect(301, 'http://example.com');724 * res.redirect('../login'); // /blog/post/1 -> /blog/login725 *726 * @api public727 */728perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 729–730why, one step back729res.redirect = function redirect(url) {730 var address = url;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 731why, one step back731 var body;perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 732why, one step back732 var status = 302;improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 733–734why, one step back733734 // allow status / urlperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 735–738why, one step back735 if (arguments.length === 2) {736 if (typeof arguments[0] === 'number') {737 status = arguments[0];738 address = arguments[1];improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
line 739why, one step back739 } else {Merge tag '3.17.8'Douglas Christopher Wilsonbefore adoption2c5ed88
line 740why, one step back740 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 741–745why, one step back741 status = arguments[1];742 }743 }744745 // Set location headerperf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 746–747why, one step back746 this.location(address);747 address = this.get('Location');improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 748–751why, one step back748749 // Support text/{plain,html} by default750 this.format({751 text: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 752why, one step back752 body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 753–755why, one step back753 },754755 html: function(){Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f
line 756why, one step back756 var u = escapeHtml(address);improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 757–767why, one step back757 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';758 },759760 default: function(){761 body = '';762 }763 });764765 // Respond766 this.statusCode = status;767 this.set('Content-Length', Buffer.byteLength(body));perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
lines 768–770why, one step back768769 if (this.req.method === 'HEAD') {770 this.end();Merge tag '4.11.2'Douglas Christopher Wilsonbefore adoptiona9ef9e1
lines 771–772why, one step back771 } else {772 this.end(body);perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203
line 773why, one step back773 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 774–780why, one step back774};775776/**777 * Add `field` to Vary. If already present in the Vary set, then778 * this call is simply ignored.779 *780 * @param {Array|String} fieldbuild: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8
line 781why, one step back781 * @return {ServerResponse} for chainingimprove before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 782–786why, one step back782 * @api public783 */784785res.vary = function(field){786 // checks for back-compatadd deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0
lines 787–790why, one step back787 if (!field || (Array.isArray(field) && !field.length)) {788 deprecate('res.vary(): Provide a field name');789 return this;790 }improve before hook in mvc exampleDouglas Christopher Wilsonbefore adoption4279e6e
lines 791–832why, one step back791792 vary(this, field);793794 return this;795};796797/**798 * Render `view` with the given `options` and optional callback `fn`.799 * When a callback function is given a response will _not_ be made800 * automatically, otherwise a response of _200_ and _text/html_ is given.801 *802 * Options:803 *804 * - `cache` boolean hinting to the engine it should cache805 * - `filename` filename of the view being rendered806 *807 * @api public808 */809810res.render = function(view, options, fn){811 options = options || {};812 var self = this;813 var req = this.req;814 var app = req.app;815816 // support callback function as second arg817 if ('function' == typeof options) {818 fn = options, options = {};819 }820821 // merge res.locals822 options._locals = self.locals;823824 // default callback to respond825 fn = fn || function(err, str){826 if (err) return req.next(err);827 self.send(str);828 };829830 // render831 app.render(view, options, fn);832};Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 833–836why, one step back833834// pipe the send file stream835function sendfile(res, file, options, callback) {836 var done = false;Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
line 837why, one step back837 var streaming;Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
line 838why, one step back838Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 839–848why, one step back839 // request aborted840 function onaborted() {841 if (done) return;842 done = true;843844 var err = new Error('Request aborted');845 err.code = 'ECONNABORT';846 callback(err);847 }848Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 849–872why, one step back849 // directory850 function ondirectory() {851 if (done) return;852 done = true;853854 var err = new Error('EISDIR, read');855 err.code = 'EISDIR';856 callback(err);857 }858859 // errors860 function onerror(err) {861 if (done) return;862 done = true;863 callback(err);864 }865866 // ended867 function onend() {868 if (done) return;869 done = true;870 callback();871 }872Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 873–877why, one step back873 // file874 function onfile() {875 streaming = false;876 }877Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 878–883why, one step back878 // finished879 function onfinish(err) {880 if (err) return onerror(err);881 if (done) return;882883 setImmediate(function () {Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 884–888why, one step back884 if (streaming !== false && !done) {885 onaborted();886 return;887 }888Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 889–890why, one step back889 if (done) return;890 done = true;Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
line 891why, one step back891 callback();Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 892–894why, one step back892 });893 }894Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 895–900why, one step back895 // streaming896 function onstream() {897 streaming = true;898 }899900 file.on('directory', ondirectory);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 901–902why, one step back901 file.on('end', onend);902 file.on('error', onerror);Merge tag '4.11.1'Douglas Christopher Wilsonbefore adoption8a5ecd3
lines 903–904why, one step back903 file.on('file', onfile);904 file.on('stream', onstream);Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a
lines 905–922why, one step back905 onFinished(res, onfinish);906907 if (options.headers) {908 // set headers on successful transfer909 file.on('headers', function headers(res) {910 var obj = options.headers;911 var keys = Object.keys(obj);912913 for (var i = 0; i < keys.length; i++) {914 var k = keys[i];915 res.setHeader(k, obj[k]);916 }917 });918 }919920 // pipe921 file.pipe(res);922}