Skip to content
Myr

response.js

This file

Path

lib/response.js

1,034 lines · 24.2 KiB · JavaScript

Last changed by

Fix res.format error when only default providedBehcet Uyarbefore adoption24d1c98

History of this file

Take it

The walk stopped after 200 commits: lines older than 6bc7574 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

perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f

lines 8–9why, one step back
8'use strict';
9

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 10–11why, one step back
10/**
11 * Module dependencies.

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 13–14why, one step back
13 */
14

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 23–121why, one step back
23var sign = require('cookie-signature').sign;
24var normalizeType = require('./utils').normalizeType;25var normalizeTypes = require('./utils').normalizeTypes;26var setCharset = require('./utils').setCharset;27var statusCodes = http.STATUS_CODES;28var cookie = require('cookie');29var send = require('send');30var extname = path.extname;31var mime = send.mime;32var resolve = path.resolve;33var vary = require('vary');3435/**36 * Response prototype.37 */3839var res = module.exports = {40 __proto__: http.ServerResponse.prototype41};4243/**44 * Set status `code`.45 *46 * @param {Number} code47 * @return {ServerResponse}48 * @api public49 */5051res.status = function(code){52 this.statusCode = code;53 return this;54};5556/**57 * Set Link header field with the given `links`.58 *59 * Examples:60 *61 * res.links({62 * next: 'http://api.example.com/users?page=2',63 * last: 'http://api.example.com/users?page=5'64 * });65 *66 * @param {Object} links67 * @return {ServerResponse}68 * @api public69 */7071res.links = function(links){72 var link = this.get('Link') || '';73 if (link) link += ', ';74 return this.set('Link', link + Object.keys(links).map(function(rel){75 return '<' + links[rel] + '>; rel="' + rel + '"';76 }).join(', '));77};7879/**80 * Send a response.81 *82 * Examples:83 *84 * res.send(new Buffer('wahoo'));85 * res.send({ some: 'json' });86 * res.send('<p>some html</p>');87 *88 * @param {string|number|boolean|object|Buffer} body89 * @api public90 */9192res.send = function send(body) {93 var chunk = body;94 var encoding;95 var len;96 var req = this.req;97 var type;9899 // settings100 var app = this.app;101102 // allow status / body103 if (arguments.length === 2) {104 // res.send(body, status) backwards compat105 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {106 deprecate('res.send(body, status): Use res.status(status).send(body) instead');107 this.statusCode = arguments[1];108 } else {109 deprecate('res.send(status, body): Use res.status(status).send(body) instead');110 this.statusCode = arguments[0];111 chunk = arguments[1];112 }113 }114115 // disambiguate res.send(status) and res.send(status, num)116 if (typeof chunk === 'number' && arguments.length === 1) {117 // res.send(status) will set status message as text string118 if (!this.get('Content-Type')) {119 this.type('txt');120 }121

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

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 123why, one step back
123 this.statusCode = chunk;

perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4

line 124why, one step back
124 chunk = statusCodes[chunk];

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 125–171why, one step back
125 }
126127 switch (typeof chunk) {128 // string defaulting to html129 case 'string':130 if (!this.get('Content-Type')) {131 this.type('html');132 }133 break;134 case 'boolean':135 case 'number':136 case 'object':137 if (chunk === null) {138 chunk = '';139 } else if (Buffer.isBuffer(chunk)) {140 if (!this.get('Content-Type')) {141 this.type('bin');142 }143 } else {144 return this.json(chunk);145 }146 break;147 }148149 // write strings in utf-8150 if (typeof chunk === 'string') {151 encoding = 'utf8';152 type = this.get('Content-Type');153154 // reflect this in content-type155 if (typeof type === 'string') {156 this.set('Content-Type', setCharset(type, 'utf-8'));157 }158 }159160 // populate Content-Length161 if (chunk !== undefined) {162 if (!Buffer.isBuffer(chunk)) {163 // convert chunk to Buffer; saves later double conversions164 chunk = new Buffer(chunk, encoding);165 encoding = undefined;166 }167168 len = chunk.length;169 this.set('Content-Length', len);170 }171

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 178–191why, one step back
178 }
179 }180181 // freshness182 if (req.fresh) this.statusCode = 304;183184 // strip irrelevant headers185 if (204 == this.statusCode || 304 == this.statusCode) {186 this.removeHeader('Content-Type');187 this.removeHeader('Content-Length');188 this.removeHeader('Transfer-Encoding');189 chunk = '';190 }191

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

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

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

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

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

lines 195–197why, one step back
195 } else {
196 // respond197 this.end(chunk, encoding);

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 198–313why, one step back
198 }
199200 return this;201};202203/**204 * Send JSON response.205 *206 * Examples:207 *208 * res.json(null);209 * res.json({ user: 'tj' });210 *211 * @param {string|number|boolean|object} obj212 * @api public213 */214215res.json = function json(obj) {216 var val = obj;217218 // allow status / body219 if (arguments.length === 2) {220 // res.json(body, status) backwards compat221 if (typeof arguments[1] === 'number') {222 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');223 this.statusCode = arguments[1];224 } else {225 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');226 this.statusCode = arguments[0];227 val = arguments[1];228 }229 }230231 // settings232 var app = this.app;233 var replacer = app.get('json replacer');234 var spaces = app.get('json spaces');235 var body = JSON.stringify(val, replacer, spaces);236237 // content-type238 if (!this.get('Content-Type')) {239 this.set('Content-Type', 'application/json');240 }241242 return this.send(body);243};244245/**246 * Send JSON response with JSONP callback support.247 *248 * Examples:249 *250 * res.jsonp(null);251 * res.jsonp({ user: 'tj' });252 *253 * @param {string|number|boolean|object} obj254 * @api public255 */256257res.jsonp = function jsonp(obj) {258 var val = obj;259260 // allow status / body261 if (arguments.length === 2) {262 // res.json(body, status) backwards compat263 if (typeof arguments[1] === 'number') {264 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');265 this.statusCode = arguments[1];266 } else {267 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');268 this.statusCode = arguments[0];269 val = arguments[1];270 }271 }272273 // settings274 var app = this.app;275 var replacer = app.get('json replacer');276 var spaces = app.get('json spaces');277 var body = JSON.stringify(val, replacer, spaces);278 var callback = this.req.query[app.get('jsonp callback name')];279280 // content-type281 if (!this.get('Content-Type')) {282 this.set('X-Content-Type-Options', 'nosniff');283 this.set('Content-Type', 'application/json');284 }285286 // fixup callback287 if (Array.isArray(callback)) {288 callback = callback[0];289 }290291 // jsonp292 if (typeof callback === 'string' && callback.length !== 0) {293 this.charset = 'utf-8';294 this.set('X-Content-Type-Options', 'nosniff');295 this.set('Content-Type', 'text/javascript');296297 // restrict callback charset298 callback = callback.replace(/[^\[\]\w$.]/g, '');299300 // replace chars not allowed in JavaScript that are in JSON301 body = body302 .replace(/\u2028/g, '\\u2028')303 .replace(/\u2029/g, '\\u2029');304305 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"306 // the typeof check is just to reduce client error noise307 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';308 }309310 return this.send(body);311};312313/**

Add res.sendStatusSeth Samuelbefore adoption12f92a5

lines 314–328why, one step back
314 * Send given HTTP status code.
315 *316 * Sets the response status to `statusCode` and the body of the317 * response to the standard description from node's http.STATUS_CODES318 * or the statusCode number if no description.319 *320 * Examples:321 *322 * res.sendStatus(200);323 *324 * @param {number} statusCode325 * @api public326 */327328res.sendStatus = function sendStatus(statusCode) {

perf: use saved reference to http.STATUS_CODESThomas Cortbefore adoption91731b4

line 329why, one step back
329 var body = statusCodes[statusCode] || String(statusCode);

Add res.sendStatusSeth Samuelbefore adoption12f92a5

lines 330–337why, one step back
330
331 this.statusCode = statusCode;332 this.type('txt');333334 return this.send(body);335};336337/**

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 338–379why, one step back
338 * Transfer the file at the given `path`.
339 *340 * Automatically sets the _Content-Type_ response header field.341 * The callback `fn(err)` is invoked when the transfer is complete342 * or when an error occurs. Be sure to check `res.sentHeader`343 * if you wish to attempt responding, as the header and some data344 * may have already been transferred.345 *346 * Options:347 *348 * - `maxAge` defaulting to 0 (can be string converted by `ms`)349 * - `root` root directory for relative filenames350 * - `headers` object of headers to serve with file351 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them352 *353 * Other options are passed along to `send`.354 *355 * Examples:356 *357 * The following example illustrates how `res.sendFile()` may358 * be used as an alternative for the `static()` middleware for359 * dynamic situations. The code backing `res.sendFile()` is actually360 * the same code, so HTTP cache support etc is identical.361 *362 * app.get('/user/:uid/photos/:file', function(req, res){363 * var uid = req.params.uid364 * , file = req.params.file;365 *366 * req.user.mayViewFilesFrom(uid, function(yes){367 * if (yes) {368 * res.sendFile('/uploads/' + uid + '/' + file);369 * } else {370 * res.send(403, 'Sorry! you cant see that.');371 * }372 * });373 * });374 *375 * @api public376 */377378res.sendFile = function sendFile(path, options, fn) {379 var req = this.req;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 381–398why, one step back
381 var next = req.next;
382383 if (!path) {384 throw new TypeError('path argument is required to res.sendFile');385 }386387 // support function as second arg388 if (typeof options === 'function') {389 fn = options;390 options = {};391 }392393 options = options || {};394395 if (!options.root && !isAbsolute(path)) {396 throw new TypeError('path must be absolute or specify root to res.sendFile');397 }398

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 407why, one step back
407

Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoptionb326ae8

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

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

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 410–412why, one step back
410 next(err);
411 }412 });

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 413–456why, one step back
413};
414415/**416 * Transfer the file at the given `path`.417 *418 * Automatically sets the _Content-Type_ response header field.419 * The callback `fn(err)` is invoked when the transfer is complete420 * or when an error occurs. Be sure to check `res.sentHeader`421 * if you wish to attempt responding, as the header and some data422 * may have already been transferred.423 *424 * Options:425 *426 * - `maxAge` defaulting to 0 (can be string converted by `ms`)427 * - `root` root directory for relative filenames428 * - `headers` object of headers to serve with file429 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them430 *431 * Other options are passed along to `send`.432 *433 * Examples:434 *435 * The following example illustrates how `res.sendfile()` may436 * be used as an alternative for the `static()` middleware for437 * dynamic situations. The code backing `res.sendfile()` is actually438 * the same code, so HTTP cache support etc is identical.439 *440 * app.get('/user/:uid/photos/:file', function(req, res){441 * var uid = req.params.uid442 * , file = req.params.file;443 *444 * req.user.mayViewFilesFrom(uid, function(yes){445 * if (yes) {446 * res.sendfile('/uploads/' + uid + '/' + file);447 * } else {448 * res.send(403, 'Sorry! you cant see that.');449 * }450 * });451 * });452 *453 * @api public454 */455456res.sendfile = function(path, options, fn){

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 460–461why, one step back
460
461 // support function as second arg

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 463–466why, one step back
463 fn = options;
464 options = {};465 }466

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 468why, one step back
468

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 471why, one step back
471

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 476why, one step back
476

Fix res.sendFile logging standard write errorsDouglas Christopher Wilsonbefore adoption4b26bbd

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 479–481why, one step back
479 next(err);
480 }481 });

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 482–608why, one step back
482};
483484res.sendfile = deprecate.function(res.sendfile,485 'res.sendfile: Use res.sendFile instead');486487/**488 * Transfer the file at the given `path` as an attachment.489 *490 * Optionally providing an alternate attachment `filename`,491 * and optional callback `fn(err)`. The callback is invoked492 * when the data transfer is complete, or when an error has493 * ocurred. Be sure to check `res.headersSent` if you plan to respond.494 *495 * This method uses `res.sendfile()`.496 *497 * @api public498 */499500res.download = function download(path, filename, fn) {501 // support function as second arg502 if (typeof filename === 'function') {503 fn = filename;504 filename = null;505 }506507 filename = filename || path;508509 // set Content-Disposition when file is sent510 var headers = {511 'Content-Disposition': contentDisposition(filename)512 };513514 // Resolve the full path for sendFile515 var fullPath = resolve(path);516517 return this.sendFile(fullPath, { headers: headers }, fn);518};519520/**521 * Set _Content-Type_ response header with `type` through `mime.lookup()`522 * when it does not contain "/", or set the Content-Type to `type` otherwise.523 *524 * Examples:525 *526 * res.type('.html');527 * res.type('html');528 * res.type('json');529 * res.type('application/json');530 * res.type('png');531 *532 * @param {String} type533 * @return {ServerResponse} for chaining534 * @api public535 */536537res.contentType =538res.type = function(type){539 return this.set('Content-Type', ~type.indexOf('/')540 ? type541 : mime.lookup(type));542};543544/**545 * Respond to the Acceptable formats using an `obj`546 * of mime-type callbacks.547 *548 * This method uses `req.accepted`, an array of549 * acceptable types ordered by their quality values.550 * When "Accept" is not present the _first_ callback551 * is invoked, otherwise the first match is used. When552 * no match is performed the server responds with553 * 406 "Not Acceptable".554 *555 * Content-Type is set for you, however if you choose556 * you may alter this within the callback using `res.type()`557 * or `res.set('Content-Type', ...)`.558 *559 * res.format({560 * 'text/plain': function(){561 * res.send('hey');562 * },563 *564 * 'text/html': function(){565 * res.send('<p>hey</p>');566 * },567 *568 * 'appliation/json': function(){569 * res.send({ message: 'hey' });570 * }571 * });572 *573 * In addition to canonicalized MIME types you may574 * also use extnames mapped to these types:575 *576 * res.format({577 * text: function(){578 * res.send('hey');579 * },580 *581 * html: function(){582 * res.send('<p>hey</p>');583 * },584 *585 * json: function(){586 * res.send({ message: 'hey' });587 * }588 * });589 *590 * By default Express passes an `Error`591 * with a `.status` of 406 to `next(err)`592 * if a match is not made. If you provide593 * a `.default` callback it will be invoked594 * instead.595 *596 * @param {Object} obj597 * @return {ServerResponse} for chaining598 * @api public599 */600601res.format = function(obj){602 var req = this.req;603 var next = req.next;604605 var fn = obj.default;606 if (fn) delete obj.default;607 var keys = Object.keys(obj);608

Fix res.format error when only default providedBehcet Uyarbefore adoption24d1c98

lines 609–611why, one step back
609 var key = keys.length > 0
610 ? req.accepts(keys)611 : false;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 612–637why, one step back
612
613 this.vary("Accept");614615 if (key) {616 this.set('Content-Type', normalizeType(key).value);617 obj[key](req, this, next);618 } else if (fn) {619 fn();620 } else {621 var err = new Error('Not Acceptable');622 err.status = 406;623 err.types = normalizeTypes(keys).map(function(o){ return o.value });624 next(err);625 }626627 return this;628};629630/**631 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.632 *633 * @param {String} filename634 * @return {ServerResponse}635 * @api public636 */637

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

lines 638–642why, one step back
638res.attachment = function attachment(filename) {
639 if (filename) {640 this.type(extname(filename));641 }642

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

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

Use content-disposition moduleDouglas Christopher Wilsonbefore adoption6f31218

line 644why, one step back
644

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 645–648why, one step back
645 return this;
646};647648/**

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

lines 649–677why, one step back
649 * Append additional header `field` with value `val`.
650 *651 * Example:652 *653 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);654 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');655 * res.append('Warning', '199 Miscellaneous warning');656 *657 * @param {String} field658 * @param {String|Array} val659 * @return {ServerResponse} for chaining660 * @api public661 */662663res.append = function append(field, val) {664 var prev = this.get(field);665 var value = val;666667 if (prev) {668 // concat the new and prev vals669 value = Array.isArray(prev) ? prev.concat(val)670 : Array.isArray(val) ? [prev].concat(val)671 : [prev, val];672 }673674 return this.set(field, value);675};676677/**

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 678–688why, one step back
678 * Set header `field` to `val`, or pass
679 * an object of header fields.680 *681 * Examples:682 *683 * res.set('Foo', ['bar', 'baz']);684 * res.set('Accept', 'application/json');685 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });686 *687 * Aliased as `res.header()`.688 *

docs: update res.set jsdocPhatbefore adoption4b70375

lines 689–690why, one step back
689 * @param {String|Object} field
690 * @param {String|Array} val

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 691–736why, one step back
691 * @return {ServerResponse} for chaining
692 * @api public693 */694695res.set =696res.header = function header(field, val) {697 if (arguments.length === 2) {698 if (Array.isArray(val)) val = val.map(String);699 else val = String(val);700 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {701 var charset = mime.charsets.lookup(val.split(';')[0]);702 if (charset) val += '; charset=' + charset.toLowerCase();703 }704 this.setHeader(field, val);705 } else {706 for (var key in field) {707 this.set(key, field[key]);708 }709 }710 return this;711};712713/**714 * Get value for header `field`.715 *716 * @param {String} field717 * @return {String}718 * @api public719 */720721res.get = function(field){722 return this.getHeader(field);723};724725/**726 * Clear cookie `name`.727 *728 * @param {String} name729 * @param {Object} options730 * @return {ServerResponse} for chaining731 * @api public732 */733734res.clearCookie = function(name, options){735 var opts = { expires: new Date(1), path: '/' };736 return this.cookie(name, '', options

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 738–765why, one step back
738 : opts);
739};740741/**742 * Set cookie `name` to `val`, with the given `options`.743 *744 * Options:745 *746 * - `maxAge` max-age in milliseconds, converted to `expires`747 * - `signed` sign the cookie748 * - `path` defaults to "/"749 *750 * Examples:751 *752 * // "Remember Me" for 15 minutes753 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });754 *755 * // save as above756 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })757 *758 * @param {String} name759 * @param {String|Object} val760 * @param {Options} options761 * @return {ServerResponse} for chaining762 * @api public763 */764765res.cookie = function(name, val, options){

Merge tag '3.18.1'Douglas Christopher Wilsonbefore adoptionccc45a7

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 767–850why, one step back
767 var secret = this.req.secret;
768 var signed = options.signed;769 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');770 if ('number' == typeof val) val = val.toString();771 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);772 if (signed) val = 's:' + sign(val, secret);773 if ('maxAge' in options) {774 options.expires = new Date(Date.now() + options.maxAge);775 options.maxAge /= 1000;776 }777 if (null == options.path) options.path = '/';778 var headerVal = cookie.serialize(name, String(val), options);779780 // supports multiple 'res.cookie' calls by getting previous value781 var prev = this.get('Set-Cookie');782 if (prev) {783 if (Array.isArray(prev)) {784 headerVal = prev.concat(headerVal);785 } else {786 headerVal = [prev, headerVal];787 }788 }789 this.set('Set-Cookie', headerVal);790 return this;791};792793794/**795 * Set the location header to `url`.796 *797 * The given `url` can also be "back", which redirects798 * to the _Referrer_ or _Referer_ headers or "/".799 *800 * Examples:801 *802 * res.location('/foo/bar').;803 * res.location('http://example.com');804 * res.location('../login');805 *806 * @param {String} url807 * @return {ServerResponse} for chaining808 * @api public809 */810811res.location = function(url){812 var req = this.req;813814 // "back" is an alias for the referrer815 if ('back' == url) url = req.get('Referrer') || '/';816817 // Respond818 this.set('Location', url);819 return this;820};821822/**823 * Redirect to the given `url` with optional response `status`824 * defaulting to 302.825 *826 * The resulting `url` is determined by `res.location()`, so827 * it will play nicely with mounted apps, relative paths,828 * `"back"` etc.829 *830 * Examples:831 *832 * res.redirect('/foo/bar');833 * res.redirect('http://example.com');834 * res.redirect(301, 'http://example.com');835 * res.redirect('../login'); // /blog/post/1 -> /blog/login836 *837 * @api public838 */839840res.redirect = function redirect(url) {841 var address = url;842 var body;843 var status = 302;844845 // allow status / url846 if (arguments.length === 2) {847 if (typeof arguments[0] === 'number') {848 status = arguments[0];849 address = arguments[1];850 } else {

Merge tag '3.17.8'Douglas Christopher Wilsonbefore adoption2c5ed88

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 852–862why, one step back
852 status = arguments[1];
853 }854 }855856 // Set location header857 this.location(address);858 address = this.get('Location');859860 // Support text/{plain,html} by default861 this.format({862 text: function(){

Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 864–866why, one step back
864 },
865866 html: function(){

Fix res.redirect body when redirect status specifiedAlex Upadhyaybefore adoption6f0302f

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 868–881why, one step back
868 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';
869 },870871 default: function(){872 body = '';873 }874 });875876 // Respond877 this.statusCode = status;878 this.set('Content-Length', Buffer.byteLength(body));879880 if (this.req.method === 'HEAD') {881 this.end();

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

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

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 884–943why, one step back
884 }
885};886887/**888 * Add `field` to Vary. If already present in the Vary set, then889 * this call is simply ignored.890 *891 * @param {Array|String} field892 * @return {ServerResponse} for chaining893 * @api public894 */895896res.vary = function(field){897 // checks for back-compat898 if (!field || (Array.isArray(field) && !field.length)) {899 deprecate('res.vary(): Provide a field name');900 return this;901 }902903 vary(this, field);904905 return this;906};907908/**909 * Render `view` with the given `options` and optional callback `fn`.910 * When a callback function is given a response will _not_ be made911 * automatically, otherwise a response of _200_ and _text/html_ is given.912 *913 * Options:914 *915 * - `cache` boolean hinting to the engine it should cache916 * - `filename` filename of the view being rendered917 *918 * @api public919 */920921res.render = function(view, options, fn){922 options = options || {};923 var self = this;924 var req = this.req;925 var app = req.app;926927 // support callback function as second arg928 if ('function' == typeof options) {929 fn = options, options = {};930 }931932 // merge res.locals933 options._locals = self.locals;934935 // default callback to respond936 fn = fn || function(err, str){937 if (err) return req.next(err);938 self.send(str);939 };940941 // render942 app.render(view, options, fn);943};

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 944–947why, one step back
944
945// pipe the send file stream946function sendfile(res, file, options, callback) {947 var done = false;

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

line 948why, one step back
948 var streaming;

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

line 949why, one step back
949

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

lines 950–955why, one step back
950 // request aborted
951 function onaborted() {952 if (done) return;953 done = true;954955 var err = new Error('Request aborted');

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

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

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

lines 957–959why, one step back
957 callback(err);
958 }959

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 960–983why, one step back
960 // directory
961 function ondirectory() {962 if (done) return;963 done = true;964965 var err = new Error('EISDIR, read');966 err.code = 'EISDIR';967 callback(err);968 }969970 // errors971 function onerror(err) {972 if (done) return;973 done = true;974 callback(err);975 }976977 // ended978 function onend() {979 if (done) return;980 done = true;981 callback();982 }983

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

lines 984–985why, one step back
984 // file
985 function onfile() {

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

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

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

lines 987–988why, one step back
987 }
988

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 989–990why, one step back
989 // finished
990 function onfinish(err) {

Fix ECONNRESET errors from res.sendFile usageDouglas Christopher Wilsonbefore adoption14a5875

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 992–995why, one step back
992 if (err) return onerror(err);
993 if (done) return;994995 setImmediate(function () {

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

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

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

lines 998–1000why, one step back
998 return;
999 }1000

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

lines 1001–1003why, one step back
1001 if (done) return;
1002 done = true;1003 callback();

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 1004–1006why, one step back
1004 });
1005 }1006

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

lines 1007–1012why, one step back
1007 // streaming
1008 function onstream() {1009 streaming = true;1010 }10111012 file.on('directory', ondirectory);

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

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

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

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

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

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

Invoke callback for sendfile when client abortsDouglas Christopher Wilsonbefore adoption2a0c35a

lines 1018–1034why, one step back
1018
1019 if (options.headers) {1020 // set headers on successful transfer1021 file.on('headers', function headers(res) {1022 var obj = options.headers;1023 var keys = Object.keys(obj);10241025 for (var i = 0; i < keys.length; i++) {1026 var k = keys[i];1027 res.setHeader(k, obj[k]);1028 }1029 });1030 }10311032 // pipe1033 file.pipe(res);1034}