Skip to content
Myr

response.js

This file

Path

lib/response.js

1,030 lines · 24.2 KiB · JavaScript

Last changed by

Fix regression where "Request aborted" is logged using res.sendFileDouglas Christopher Wilsonbefore adoption7e0afa8

History of this file

Take it

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

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

lines 1–7why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */7

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 8–9why, one step back
8/**
9 * Module dependencies.

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

line 10why, one step back
10 * @api private

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 11–12why, one step back
11 */
12

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

line 13why, one step back
13var contentDisposition = require('content-disposition');

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 14–17why, one step back
14var deprecate = require('depd')('express');
15var escapeHtml = require('escape-html');16var http = require('http');17var isAbsolute = require('./utils').isAbsolute;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 18why, one step back
18var onFinished = require('on-finished');

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 19why, one step back
19var path = require('path');

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 20why, one step back
20var merge = require('utils-merge');

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 21–119why, one step back
21var sign = require('cookie-signature').sign;
22var normalizeType = require('./utils').normalizeType;23var normalizeTypes = require('./utils').normalizeTypes;24var setCharset = require('./utils').setCharset;25var statusCodes = http.STATUS_CODES;26var cookie = require('cookie');27var send = require('send');28var extname = path.extname;29var mime = send.mime;30var resolve = path.resolve;31var vary = require('vary');3233/**34 * Response prototype.35 */3637var res = module.exports = {38 __proto__: http.ServerResponse.prototype39};4041/**42 * Set status `code`.43 *44 * @param {Number} code45 * @return {ServerResponse}46 * @api public47 */4849res.status = function(code){50 this.statusCode = code;51 return this;52};5354/**55 * Set Link header field with the given `links`.56 *57 * Examples:58 *59 * res.links({60 * next: 'http://api.example.com/users?page=2',61 * last: 'http://api.example.com/users?page=5'62 * });63 *64 * @param {Object} links65 * @return {ServerResponse}66 * @api public67 */6869res.links = function(links){70 var link = this.get('Link') || '';71 if (link) link += ', ';72 return this.set('Link', link + Object.keys(links).map(function(rel){73 return '<' + links[rel] + '>; rel="' + rel + '"';74 }).join(', '));75};7677/**78 * Send a response.79 *80 * Examples:81 *82 * res.send(new Buffer('wahoo'));83 * res.send({ some: 'json' });84 * res.send('<p>some html</p>');85 *86 * @param {string|number|boolean|object|Buffer} body87 * @api public88 */8990res.send = function send(body) {91 var chunk = body;92 var encoding;93 var len;94 var req = this.req;95 var type;9697 // settings98 var app = this.app;99100 // allow status / body101 if (arguments.length === 2) {102 // res.send(body, status) backwards compat103 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {104 deprecate('res.send(body, status): Use res.status(status).send(body) instead');105 this.statusCode = arguments[1];106 } else {107 deprecate('res.send(status, body): Use res.status(status).send(body) instead');108 this.statusCode = arguments[0];109 chunk = arguments[1];110 }111 }112113 // disambiguate res.send(status) and res.send(status, num)114 if (typeof chunk === 'number' && arguments.length === 1) {115 // res.send(status) will set status message as text string116 if (!this.get('Content-Type')) {117 this.type('txt');118 }119

Fix res.send to mention res.sendStatusDouglas Christopher Wilsonbefore adoption4dd9705

line 120why, one step back
120 deprecate('res.send(status): Use res.sendStatus(status) instead');

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 121–169why, one step back
121 this.statusCode = chunk;
122 chunk = http.STATUS_CODES[chunk];123 }124125 switch (typeof chunk) {126 // string defaulting to html127 case 'string':128 if (!this.get('Content-Type')) {129 this.type('html');130 }131 break;132 case 'boolean':133 case 'number':134 case 'object':135 if (chunk === null) {136 chunk = '';137 } else if (Buffer.isBuffer(chunk)) {138 if (!this.get('Content-Type')) {139 this.type('bin');140 }141 } else {142 return this.json(chunk);143 }144 break;145 }146147 // write strings in utf-8148 if (typeof chunk === 'string') {149 encoding = 'utf8';150 type = this.get('Content-Type');151152 // reflect this in content-type153 if (typeof type === 'string') {154 this.set('Content-Type', setCharset(type, 'utf-8'));155 }156 }157158 // populate Content-Length159 if (chunk !== undefined) {160 if (!Buffer.isBuffer(chunk)) {161 // convert chunk to Buffer; saves later double conversions162 chunk = new Buffer(chunk, encoding);163 encoding = undefined;164 }165166 len = chunk.length;167 this.set('Content-Length', len);168 }169

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

lines 170–175why, one step back
170 // populate ETag
171 var etag;172 var generateETag = len !== undefined && app.get('etag fn');173 if (typeof generateETag === 'function' && !this.get('ETag')) {174 if ((etag = generateETag(chunk, encoding))) {175 this.set('ETag', etag);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 176–189why, one step back
176 }
177 }178179 // freshness180 if (req.fresh) this.statusCode = 304;181182 // strip irrelevant headers183 if (204 == this.statusCode || 304 == this.statusCode) {184 this.removeHeader('Content-Type');185 this.removeHeader('Content-Length');186 this.removeHeader('Transfer-Encoding');187 chunk = '';188 }189

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

line 190why, one step back
190 if (req.method === 'HEAD') {

Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d

line 191why, one step back
191 // skip body for HEAD

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 192why, one step back
192 this.end();

Fix res.send double-calling res.end for HEAD requestsDouglas Christopher Wilsonbefore adoptionc24463d

lines 193–195why, one step back
193 } else {
194 // respond195 this.end(chunk, encoding);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 196–311why, one step back
196 }
197198 return this;199};200201/**202 * Send JSON response.203 *204 * Examples:205 *206 * res.json(null);207 * res.json({ user: 'tj' });208 *209 * @param {string|number|boolean|object} obj210 * @api public211 */212213res.json = function json(obj) {214 var val = obj;215216 // allow status / body217 if (arguments.length === 2) {218 // res.json(body, status) backwards compat219 if (typeof arguments[1] === 'number') {220 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');221 this.statusCode = arguments[1];222 } else {223 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');224 this.statusCode = arguments[0];225 val = arguments[1];226 }227 }228229 // settings230 var app = this.app;231 var replacer = app.get('json replacer');232 var spaces = app.get('json spaces');233 var body = JSON.stringify(val, replacer, spaces);234235 // content-type236 if (!this.get('Content-Type')) {237 this.set('Content-Type', 'application/json');238 }239240 return this.send(body);241};242243/**244 * Send JSON response with JSONP callback support.245 *246 * Examples:247 *248 * res.jsonp(null);249 * res.jsonp({ user: 'tj' });250 *251 * @param {string|number|boolean|object} obj252 * @api public253 */254255res.jsonp = function jsonp(obj) {256 var val = obj;257258 // allow status / body259 if (arguments.length === 2) {260 // res.json(body, status) backwards compat261 if (typeof arguments[1] === 'number') {262 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');263 this.statusCode = arguments[1];264 } else {265 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');266 this.statusCode = arguments[0];267 val = arguments[1];268 }269 }270271 // settings272 var app = this.app;273 var replacer = app.get('json replacer');274 var spaces = app.get('json spaces');275 var body = JSON.stringify(val, replacer, spaces);276 var callback = this.req.query[app.get('jsonp callback name')];277278 // content-type279 if (!this.get('Content-Type')) {280 this.set('X-Content-Type-Options', 'nosniff');281 this.set('Content-Type', 'application/json');282 }283284 // fixup callback285 if (Array.isArray(callback)) {286 callback = callback[0];287 }288289 // jsonp290 if (typeof callback === 'string' && callback.length !== 0) {291 this.charset = 'utf-8';292 this.set('X-Content-Type-Options', 'nosniff');293 this.set('Content-Type', 'text/javascript');294295 // restrict callback charset296 callback = callback.replace(/[^\[\]\w$.]/g, '');297298 // replace chars not allowed in JavaScript that are in JSON299 body = body300 .replace(/\u2028/g, '\\u2028')301 .replace(/\u2029/g, '\\u2029');302303 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"304 // the typeof check is just to reduce client error noise305 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';306 }307308 return this.send(body);309};310311/**

Add res.sendStatusSeth Samuelbefore adoption12f92a5

lines 312–335why, one step back
312 * Send given HTTP status code.
313 *314 * Sets the response status to `statusCode` and the body of the315 * response to the standard description from node's http.STATUS_CODES316 * or the statusCode number if no description.317 *318 * Examples:319 *320 * res.sendStatus(200);321 *322 * @param {number} statusCode323 * @api public324 */325326res.sendStatus = function sendStatus(statusCode) {327 var body = http.STATUS_CODES[statusCode] || String(statusCode);328329 this.statusCode = statusCode;330 this.type('txt');331332 return this.send(body);333};334335/**

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 336–377why, one step back
336 * Transfer the file at the given `path`.
337 *338 * Automatically sets the _Content-Type_ response header field.339 * The callback `fn(err)` is invoked when the transfer is complete340 * or when an error occurs. Be sure to check `res.sentHeader`341 * if you wish to attempt responding, as the header and some data342 * may have already been transferred.343 *344 * Options:345 *346 * - `maxAge` defaulting to 0 (can be string converted by `ms`)347 * - `root` root directory for relative filenames348 * - `headers` object of headers to serve with file349 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them350 *351 * Other options are passed along to `send`.352 *353 * Examples:354 *355 * The following example illustrates how `res.sendFile()` may356 * be used as an alternative for the `static()` middleware for357 * dynamic situations. The code backing `res.sendFile()` is actually358 * the same code, so HTTP cache support etc is identical.359 *360 * app.get('/user/:uid/photos/:file', function(req, res){361 * var uid = req.params.uid362 * , file = req.params.file;363 *364 * req.user.mayViewFilesFrom(uid, function(yes){365 * if (yes) {366 * res.sendFile('/uploads/' + uid + '/' + file);367 * } else {368 * res.send(403, 'Sorry! you cant see that.');369 * }370 * });371 * });372 *373 * @api public374 */375376res.sendFile = function sendFile(path, options, fn) {377 var req = this.req;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 378why, one step back
378 var res = this;

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 379–396why, one step back
379 var next = req.next;
380381 if (!path) {382 throw new TypeError('path argument is required to res.sendFile');383 }384385 // support function as second arg386 if (typeof options === 'function') {387 fn = options;388 options = {};389 }390391 options = options || {};392393 if (!options.root && !isAbsolute(path)) {394 throw new TypeError('path must be absolute or specify root to res.sendFile');395 }396

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 397why, one step back
397 // create file stream

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 398–400why, one step back
398 var pathname = encodeURI(path);
399 var file = send(req, pathname, options);400

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 401–404why, one step back
401 // transfer
402 sendfile(res, file, options, function (err) {403 if (fn) return fn(err);404 if (err && err.code === 'EISDIR') return next();

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 405why, one step back
405

Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoptionb326ae8

line 406why, one step back
406 // next() all but write errors

Fix regression where "Request aborted" is logged using res.sendFileDouglas Christopher Wilsonbefore adoption7e0afa8

line 407why, one step back
407 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 408–410why, one step back
408 next(err);
409 }410 });

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 411–454why, one step back
411};
412413/**414 * Transfer the file at the given `path`.415 *416 * Automatically sets the _Content-Type_ response header field.417 * The callback `fn(err)` is invoked when the transfer is complete418 * or when an error occurs. Be sure to check `res.sentHeader`419 * if you wish to attempt responding, as the header and some data420 * may have already been transferred.421 *422 * Options:423 *424 * - `maxAge` defaulting to 0 (can be string converted by `ms`)425 * - `root` root directory for relative filenames426 * - `headers` object of headers to serve with file427 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them428 *429 * Other options are passed along to `send`.430 *431 * Examples:432 *433 * The following example illustrates how `res.sendfile()` may434 * be used as an alternative for the `static()` middleware for435 * dynamic situations. The code backing `res.sendfile()` is actually436 * the same code, so HTTP cache support etc is identical.437 *438 * app.get('/user/:uid/photos/:file', function(req, res){439 * var uid = req.params.uid440 * , file = req.params.file;441 *442 * req.user.mayViewFilesFrom(uid, function(yes){443 * if (yes) {444 * res.sendfile('/uploads/' + uid + '/' + file);445 * } else {446 * res.send(403, 'Sorry! you cant see that.');447 * }448 * });449 * });450 *451 * @api public452 */453454res.sendfile = function(path, options, fn){

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 455–457why, one step back
455 var req = this.req;
456 var res = this;457 var next = req.next;

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 458–459why, one step back
458
459 // support function as second arg

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 460why, one step back
460 if (typeof options === 'function') {

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 461–464why, one step back
461 fn = options;
462 options = {};463 }464

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 465why, one step back
465 options = options || {};

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 466why, one step back
466

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 467–468why, one step back
467 // create file stream
468 var file = send(req, path, options);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 469why, one step back
469

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 470–471why, one step back
470 // transfer
471 sendfile(res, file, options, function (err) {

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 472why, one step back
472 if (fn) return fn(err);

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 473why, one step back
473 if (err && err.code === 'EISDIR') return next();

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 474why, one step back
474

Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoption4b26bbd

lines 475–476why, one step back
475 // next() all but write errors
476 if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') {

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 477–479why, one step back
477 next(err);
478 }479 });

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 480–633why, one step back
480};
481482res.sendfile = deprecate.function(res.sendfile,483 'res.sendfile: Use res.sendFile instead');484485/**486 * Transfer the file at the given `path` as an attachment.487 *488 * Optionally providing an alternate attachment `filename`,489 * and optional callback `fn(err)`. The callback is invoked490 * when the data transfer is complete, or when an error has491 * ocurred. Be sure to check `res.headersSent` if you plan to respond.492 *493 * This method uses `res.sendfile()`.494 *495 * @api public496 */497498res.download = function download(path, filename, fn) {499 // support function as second arg500 if (typeof filename === 'function') {501 fn = filename;502 filename = null;503 }504505 filename = filename || path;506507 // set Content-Disposition when file is sent508 var headers = {509 'Content-Disposition': contentDisposition(filename)510 };511512 // Resolve the full path for sendFile513 var fullPath = resolve(path);514515 return this.sendFile(fullPath, { headers: headers }, fn);516};517518/**519 * Set _Content-Type_ response header with `type` through `mime.lookup()`520 * when it does not contain "/", or set the Content-Type to `type` otherwise.521 *522 * Examples:523 *524 * res.type('.html');525 * res.type('html');526 * res.type('json');527 * res.type('application/json');528 * res.type('png');529 *530 * @param {String} type531 * @return {ServerResponse} for chaining532 * @api public533 */534535res.contentType =536res.type = function(type){537 return this.set('Content-Type', ~type.indexOf('/')538 ? type539 : mime.lookup(type));540};541542/**543 * Respond to the Acceptable formats using an `obj`544 * of mime-type callbacks.545 *546 * This method uses `req.accepted`, an array of547 * acceptable types ordered by their quality values.548 * When "Accept" is not present the _first_ callback549 * is invoked, otherwise the first match is used. When550 * no match is performed the server responds with551 * 406 "Not Acceptable".552 *553 * Content-Type is set for you, however if you choose554 * you may alter this within the callback using `res.type()`555 * or `res.set('Content-Type', ...)`.556 *557 * res.format({558 * 'text/plain': function(){559 * res.send('hey');560 * },561 *562 * 'text/html': function(){563 * res.send('<p>hey</p>');564 * },565 *566 * 'appliation/json': function(){567 * res.send({ message: 'hey' });568 * }569 * });570 *571 * In addition to canonicalized MIME types you may572 * also use extnames mapped to these types:573 *574 * res.format({575 * text: function(){576 * res.send('hey');577 * },578 *579 * html: function(){580 * res.send('<p>hey</p>');581 * },582 *583 * json: function(){584 * res.send({ message: 'hey' });585 * }586 * });587 *588 * By default Express passes an `Error`589 * with a `.status` of 406 to `next(err)`590 * if a match is not made. If you provide591 * a `.default` callback it will be invoked592 * instead.593 *594 * @param {Object} obj595 * @return {ServerResponse} for chaining596 * @api public597 */598599res.format = function(obj){600 var req = this.req;601 var next = req.next;602603 var fn = obj.default;604 if (fn) delete obj.default;605 var keys = Object.keys(obj);606607 var key = req.accepts(keys);608609 this.vary("Accept");610611 if (key) {612 this.set('Content-Type', normalizeType(key).value);613 obj[key](req, this, next);614 } else if (fn) {615 fn();616 } else {617 var err = new Error('Not Acceptable');618 err.status = 406;619 err.types = normalizeTypes(keys).map(function(o){ return o.value });620 next(err);621 }622623 return this;624};625626/**627 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.628 *629 * @param {String} filename630 * @return {ServerResponse}631 * @api public632 */633

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

lines 634–638why, one step back
634res.attachment = function attachment(filename) {
635 if (filename) {636 this.type(extname(filename));637 }638

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

line 639why, one step back
639 this.set('Content-Disposition', contentDisposition(filename));

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

line 640why, one step back
640

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 641–644why, one step back
641 return this;
642};643644/**

Add res.append(field, val) to append headersDouglas Christopher Wilsonbefore adoptionf6f78e5

lines 645–673why, one step back
645 * Append additional header `field` with value `val`.
646 *647 * Example:648 *649 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);650 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');651 * res.append('Warning', '199 Miscellaneous warning');652 *653 * @param {String} field654 * @param {String|Array} val655 * @return {ServerResponse} for chaining656 * @api public657 */658659res.append = function append(field, val) {660 var prev = this.get(field);661 var value = val;662663 if (prev) {664 // concat the new and prev vals665 value = Array.isArray(prev) ? prev.concat(val)666 : Array.isArray(val) ? [prev].concat(val)667 : [prev, val];668 }669670 return this.set(field, value);671};672673/**

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 674–732why, one step back
674 * Set header `field` to `val`, or pass
675 * an object of header fields.676 *677 * Examples:678 *679 * res.set('Foo', ['bar', 'baz']);680 * res.set('Accept', 'application/json');681 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });682 *683 * Aliased as `res.header()`.684 *685 * @param {String|Object|Array} field686 * @param {String} val687 * @return {ServerResponse} for chaining688 * @api public689 */690691res.set =692res.header = function header(field, val) {693 if (arguments.length === 2) {694 if (Array.isArray(val)) val = val.map(String);695 else val = String(val);696 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {697 var charset = mime.charsets.lookup(val.split(';')[0]);698 if (charset) val += '; charset=' + charset.toLowerCase();699 }700 this.setHeader(field, val);701 } else {702 for (var key in field) {703 this.set(key, field[key]);704 }705 }706 return this;707};708709/**710 * Get value for header `field`.711 *712 * @param {String} field713 * @return {String}714 * @api public715 */716717res.get = function(field){718 return this.getHeader(field);719};720721/**722 * Clear cookie `name`.723 *724 * @param {String} name725 * @param {Object} options726 * @return {ServerResponse} for chaining727 * @api public728 */729730res.clearCookie = function(name, options){731 var opts = { expires: new Date(1), path: '/' };732 return this.cookie(name, '', options

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 733why, one step back
733 ? merge(opts, options)

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 734–761why, one step back
734 : opts);
735};736737/**738 * Set cookie `name` to `val`, with the given `options`.739 *740 * Options:741 *742 * - `maxAge` max-age in milliseconds, converted to `expires`743 * - `signed` sign the cookie744 * - `path` defaults to "/"745 *746 * Examples:747 *748 * // "Remember Me" for 15 minutes749 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });750 *751 * // save as above752 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })753 *754 * @param {String} name755 * @param {String|Object} val756 * @param {Options} options757 * @return {ServerResponse} for chaining758 * @api public759 */760761res.cookie = function(name, val, options){

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

line 762why, one step back
762 options = merge({}, options);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 763–846why, one step back
763 var secret = this.req.secret;
764 var signed = options.signed;765 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');766 if ('number' == typeof val) val = val.toString();767 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);768 if (signed) val = 's:' + sign(val, secret);769 if ('maxAge' in options) {770 options.expires = new Date(Date.now() + options.maxAge);771 options.maxAge /= 1000;772 }773 if (null == options.path) options.path = '/';774 var headerVal = cookie.serialize(name, String(val), options);775776 // supports multiple 'res.cookie' calls by getting previous value777 var prev = this.get('Set-Cookie');778 if (prev) {779 if (Array.isArray(prev)) {780 headerVal = prev.concat(headerVal);781 } else {782 headerVal = [prev, headerVal];783 }784 }785 this.set('Set-Cookie', headerVal);786 return this;787};788789790/**791 * Set the location header to `url`.792 *793 * The given `url` can also be "back", which redirects794 * to the _Referrer_ or _Referer_ headers or "/".795 *796 * Examples:797 *798 * res.location('/foo/bar').;799 * res.location('http://example.com');800 * res.location('../login');801 *802 * @param {String} url803 * @return {ServerResponse} for chaining804 * @api public805 */806807res.location = function(url){808 var req = this.req;809810 // "back" is an alias for the referrer811 if ('back' == url) url = req.get('Referrer') || '/';812813 // Respond814 this.set('Location', url);815 return this;816};817818/**819 * Redirect to the given `url` with optional response `status`820 * defaulting to 302.821 *822 * The resulting `url` is determined by `res.location()`, so823 * it will play nicely with mounted apps, relative paths,824 * `"back"` etc.825 *826 * Examples:827 *828 * res.redirect('/foo/bar');829 * res.redirect('http://example.com');830 * res.redirect(301, 'http://example.com');831 * res.redirect('../login'); // /blog/post/1 -> /blog/login832 *833 * @api public834 */835836res.redirect = function redirect(url) {837 var address = url;838 var body;839 var status = 302;840841 // allow status / url842 if (arguments.length === 2) {843 if (typeof arguments[0] === 'number') {844 status = arguments[0];845 address = arguments[1];846 } else {

Merge tag '3.17.8'Douglas Christopher Wilsonbefore adoption2c5ed88

line 847why, one step back
847 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 848–858why, one step back
848 status = arguments[1];
849 }850 }851852 // Set location header853 this.location(address);854 address = this.get('Location');855856 // Support text/{plain,html} by default857 this.format({858 text: function(){

Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f

line 859why, one step back
859 body = statusCodes[status] + '. Redirecting to ' + encodeURI(address);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 860–862why, one step back
860 },
861862 html: function(){

Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f

line 863why, one step back
863 var u = escapeHtml(address);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 864–877why, one step back
864 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
865 },866867 default: function(){868 body = '';869 }870 });871872 // Respond873 this.statusCode = status;874 this.set('Content-Length', Buffer.byteLength(body));875876 if (this.req.method === 'HEAD') {877 this.end();

Fix res.redirect double-calling res.end for HEAD requestsKevin Shaybefore adoption2ccb6cf

lines 878–879why, one step back
878 } else {
879 this.end(body);

deps: qs@1.2.2Douglas Christopher Wilsonbefore adoptionad3ca25

lines 880–939why, one step back
880 }
881};882883/**884 * Add `field` to Vary. If already present in the Vary set, then885 * this call is simply ignored.886 *887 * @param {Array|String} field888 * @return {ServerResponse} for chaining889 * @api public890 */891892res.vary = function(field){893 // checks for back-compat894 if (!field || (Array.isArray(field) && !field.length)) {895 deprecate('res.vary(): Provide a field name');896 return this;897 }898899 vary(this, field);900901 return this;902};903904/**905 * Render `view` with the given `options` and optional callback `fn`.906 * When a callback function is given a response will _not_ be made907 * automatically, otherwise a response of _200_ and _text/html_ is given.908 *909 * Options:910 *911 * - `cache` boolean hinting to the engine it should cache912 * - `filename` filename of the view being rendered913 *914 * @api public915 */916917res.render = function(view, options, fn){918 options = options || {};919 var self = this;920 var req = this.req;921 var app = req.app;922923 // support callback function as second arg924 if ('function' == typeof options) {925 fn = options, options = {};926 }927928 // merge res.locals929 options._locals = self.locals;930931 // default callback to respond932 fn = fn || function(err, str){933 if (err) return req.next(err);934 self.send(str);935 };936937 // render938 app.render(view, options, fn);939};

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 940–943why, one step back
940
941// pipe the send file stream942function sendfile(res, file, options, callback) {943 var done = false;

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 944why, one step back
944 var streaming;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 945why, one step back
945

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 946–951why, one step back
946 // request aborted
947 function onaborted() {948 if (done) return;949 done = true;950951 var err = new Error('Request aborted');

Fix wrong code on aborted connections from res.sendFileDouglas Christopher Wilsonbefore adoptiondbc61fc

line 952why, one step back
952 err.code = 'ECONNABORTED';

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 953–955why, one step back
953 callback(err);
954 }955

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 956–979why, one step back
956 // directory
957 function ondirectory() {958 if (done) return;959 done = true;960961 var err = new Error('EISDIR, read');962 err.code = 'EISDIR';963 callback(err);964 }965966 // errors967 function onerror(err) {968 if (done) return;969 done = true;970 callback(err);971 }972973 // ended974 function onend() {975 if (done) return;976 done = true;977 callback();978 }979

Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916

lines 980–981why, one step back
980 // file
981 function onfile() {

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 982why, one step back
982 streaming = false;

Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916

lines 983–984why, one step back
983 }
984

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 985–986why, one step back
985 // finished
986 function onfinish(err) {

Fix ECONNRESET errors from res.sendFile usageDouglas Christopher Wilsonbefore adoption14a5875

line 987why, one step back
987 if (err && err.code === 'ECONNRESET') return onaborted();

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 988–991why, one step back
988 if (err) return onerror(err);
989 if (done) return;990991 setImmediate(function () {

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 992–993why, one step back
992 if (streaming !== false && !done) {
993 onaborted();

Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916

lines 994–996why, one step back
994 return;
995 }996

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

lines 997–999why, one step back
997 if (done) return;
998 done = true;999 callback();

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 1000–1002why, one step back
1000 });
1001 }1002

Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916

lines 1003–1008why, one step back
1003 // streaming
1004 function onstream() {1005 streaming = true;1006 }10071008 file.on('directory', ondirectory);

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 1009–1010why, one step back
1009 file.on('end', onend);
1010 file.on('error', onerror);

Fix incorrect "Request aborted" for res.sendFile when HEAD or 304Douglas Christopher Wilsonbefore adoption3387916

lines 1011–1012why, one step back
1011 file.on('file', onfile);
1012 file.on('stream', onstream);

Fix res.sendFile not always detecting aborted connectionDouglas Christopher Wilsonbefore adoption5312a99

line 1013why, one step back
1013 onFinished(res, onfinish);

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 1014–1030why, one step back
1014
1015 if (options.headers) {1016 // set headers on successful transfer1017 file.on('headers', function headers(res) {1018 var obj = options.headers;1019 var keys = Object.keys(obj);10201021 for (var i = 0; i < keys.length; i++) {1022 var k = keys[i];1023 res.setHeader(k, obj[k]);1024 }1025 });1026 }10271028 // pipe1029 file.pipe(res);1030}