Skip to content
Myr

response.js

This file

Path

lib/response.js

841 lines · 19.5 KiB · JavaScript

Last changed by

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

History of this file

Take it

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

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 1–4why, one step back
1/**
2 * Module dependencies.3 */4

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

line 5why, one step back
5var deprecate = require('depd')('express');

Merge tag '3.10.0'Douglas Christopher Wilsonbefore adoption402ec83

line 6why, one step back
6var escapeHtml = require('escape-html');

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 7–12why, one step back
7var http = require('http');
8var path = require('path');9var mixin = require('utils-merge');10var sign = require('cookie-signature').sign;11var normalizeType = require('./utils').normalizeType;12var normalizeTypes = require('./utils').normalizeTypes;

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 13why, one step back
13var setCharset = require('./utils').setCharset;

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

line 14why, one step back
14var contentDisposition = require('./utils').contentDisposition;

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 15–20why, one step back
15var statusCodes = http.STATUS_CODES;
16var cookie = require('cookie');17var send = require('send');18var basename = path.basename;19var extname = path.extname;20var mime = send.mime;

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

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

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 22–80why, one step back
22
23/**24 * Response prototype.25 */2627var res = module.exports = {28 __proto__: http.ServerResponse.prototype29};3031/**32 * Set status `code`.33 *34 * @param {Number} code35 * @return {ServerResponse}36 * @api public37 */3839res.status = function(code){40 this.statusCode = code;41 return this;42};4344/**45 * Set Link header field with the given `links`.46 *47 * Examples:48 *49 * res.links({50 * next: 'http://api.example.com/users?page=2',51 * last: 'http://api.example.com/users?page=5'52 * });53 *54 * @param {Object} links55 * @return {ServerResponse}56 * @api public57 */5859res.links = function(links){60 var link = this.get('Link') || '';61 if (link) link += ', ';62 return this.set('Link', link + Object.keys(links).map(function(rel){63 return '<' + links[rel] + '>; rel="' + rel + '"';64 }).join(', '));65};6667/**68 * Send a response.69 *70 * Examples:71 *72 * res.send(new Buffer('wahoo'));73 * res.send({ some: 'json' });74 * res.send('<p>some html</p>');75 * res.send(404, 'Sorry, cant find that');76 * res.send(404);77 *78 * @api public79 */80

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 81–82why, one step back
81res.send = function send(body) {
82 var chunk = body;

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 83why, one step back
83 var encoding;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 84why, one step back
84 var len;

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 85–86why, one step back
85 var req = this.req;
86 var type;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 87–91why, one step back
87
88 // settings89 var app = this.app;9091 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 92why, one step back
92 if (arguments.length === 2) {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 93why, one step back
93 // res.send(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 94why, one step back
94 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {

add deprecation message to res.send(body, status)Douglas Christopher Wilsonbefore adoptionba8a4c5

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

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 96–97why, one step back
96 this.statusCode = arguments[1];
97 } else {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 98–99why, one step back
98 this.statusCode = arguments[0];
99 chunk = arguments[1];

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 100–102why, one step back
100 }
101 }102

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 103why, one step back
103 // disambiguate res.send(status) and res.send(status, num)

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 104why, one step back
104 if (typeof chunk === 'number' && arguments.length === 1) {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 105why, one step back
105 // res.send(status) will set status message as text string

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 106–111why, one step back
106 if (!this.get('Content-Type')) {
107 this.type('txt');108 }109110 this.statusCode = chunk;111 chunk = http.STATUS_CODES[chunk];

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 112–113why, one step back
112 }
113

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 114why, one step back
114 switch (typeof chunk) {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 115–116why, one step back
115 // string defaulting to html
116 case 'string':

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 117–119why, one step back
117 if (!this.get('Content-Type')) {
118 this.type('html');119 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 120–121why, one step back
120 break;
121 case 'boolean':

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

line 122why, one step back
122 case 'number':

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

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

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 124–129why, one step back
124 if (chunk === null) {
125 chunk = '';126 } else if (Buffer.isBuffer(chunk)) {127 if (!this.get('Content-Type')) {128 this.type('bin');129 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 130why, one step back
130 } else {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 131why, one step back
131 return this.json(chunk);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 132–135why, one step back
132 }
133 break;134 }135

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 136why, one step back
136 // write strings in utf-8

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 137why, one step back
137 if (typeof chunk === 'string') {

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 138–141why, one step back
138 encoding = 'utf8';
139 type = this.get('Content-Type');140141 // reflect this in content-type

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 142why, one step back
142 if (typeof type === 'string') {

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 143why, one step back
143 this.set('Content-Type', setCharset(type, 'utf-8'));

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 144–147why, one step back
144 }
145 }146147 // populate Content-Length

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 148–155why, one step back
148 if (chunk !== undefined) {
149 if (!Buffer.isBuffer(chunk)) {150 // convert chunk to Buffer; saves later double conversions151 chunk = new Buffer(chunk, encoding);152 encoding = undefined;153 }154155 len = chunk.length;

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

lines 156–158why, one step back
156 this.set('Content-Length', len);
157 }158

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 159–161why, one step back
159 // method check
160 var isHead = req.method === 'HEAD';161

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 162why, one step back
162 // ETag support

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

lines 163–165why, one step back
163 if (len !== undefined && (isHead || req.method === 'GET')) {
164 var etag = app.get('etag fn');165 if (etag && !this.get('ETag')) {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 166why, one step back
166 etag = etag(chunk, encoding);

Merge tag '3.9.0'Douglas Christopher Wilsonbefore adoptiondb4448d

line 167why, one step back
167 etag && this.set('ETag', etag);

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

lines 168–170why, one step back
168 }
169 }170

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 171–178why, one step back
171 // freshness
172 if (req.fresh) this.statusCode = 304;173174 // strip irrelevant headers175 if (204 == this.statusCode || 304 == this.statusCode) {176 this.removeHeader('Content-Type');177 this.removeHeader('Content-Length');178 this.removeHeader('Transfer-Encoding');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 179why, one step back
179 chunk = '';

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 180–181why, one step back
180 }
181

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

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

perf: prevent multiple Buffer creation in res.sendDouglas Christopher Wilsonbefore adoptionb43205c

line 183why, one step back
183 if (isHead) {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 184–186why, one step back
184 this.end();
185 }186

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 187why, one step back
187 // respond

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 188why, one step back
188 this.end(chunk, encoding);

Merge tag '3.8.0'Douglas Christopher Wilsonbefore adoptiondb4a061

line 189why, one step back
189

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 190–205why, one step back
190 return this;
191};192193/**194 * Send JSON response.195 *196 * Examples:197 *198 * res.json(null);199 * res.json({ user: 'tj' });200 * res.json(500, 'oh noes!');201 * res.json(404, 'I dont have that');202 *203 * @api public204 */205

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 206–208why, one step back
206res.json = function json(obj) {
207 var val = obj;208

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 209why, one step back
209 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 210why, one step back
210 if (arguments.length === 2) {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 211why, one step back
211 // res.json(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 212why, one step back
212 if (typeof arguments[1] === 'number') {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 213why, one step back
213 this.statusCode = arguments[1];

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 214why, one step back
214 if (typeof arguments[0] === 'number') {

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

lines 215–218why, one step back
215 deprecate('res.json(obj, status): Use res.json(status, obj) instead');
216 } else {217 deprecate('res.json(num, status): Use res.status(status).json(num) instead');218 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 219why, one step back
219 } else {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 220–221why, one step back
220 this.statusCode = arguments[0];
221 val = arguments[1];

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 222–228why, one step back
222 }
223 }224225 // settings226 var app = this.app;227 var replacer = app.get('json replacer');228 var spaces = app.get('json spaces');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 229why, one step back
229 var body = JSON.stringify(val, replacer, spaces);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 230–231why, one step back
230
231 // content-type

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 232–234why, one step back
232 if (!this.get('Content-Type')) {
233 this.set('Content-Type', 'application/json');234 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 235–251why, one step back
235
236 return this.send(body);237};238239/**240 * Send JSON response with JSONP callback support.241 *242 * Examples:243 *244 * res.jsonp(null);245 * res.jsonp({ user: 'tj' });246 * res.jsonp(500, 'oh noes!');247 * res.jsonp(404, 'I dont have that');248 *249 * @api public250 */251

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 252–254why, one step back
252res.jsonp = function jsonp(obj) {
253 var val = obj;254

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 255why, one step back
255 // allow status / body

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 256why, one step back
256 if (arguments.length === 2) {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 257why, one step back
257 // res.json(body, status) backwards compat

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 258why, one step back
258 if (typeof arguments[1] === 'number') {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 259why, one step back
259 this.statusCode = arguments[1];

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 260why, one step back
260 if (typeof arguments[0] === 'number') {

Merge tag '3.12.0'Douglas Christopher Wilsonbefore adoption3ffceff

lines 261–264why, one step back
261 deprecate('res.jsonp(obj, status): Use res.jsonp(status, obj) instead');
262 } else {263 deprecate('res.jsonp(num, status): Use res.status(status).jsonp(num) instead');264 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 265why, one step back
265 } else {

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 266–267why, one step back
266 this.statusCode = arguments[0];
267 val = arguments[1];

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 268–274why, one step back
268 }
269 }270271 // settings272 var app = this.app;273 var replacer = app.get('json replacer');274 var spaces = app.get('json spaces');

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 275why, one step back
275 var body = JSON.stringify(val, replacer, spaces);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 276–278why, one step back
276 var callback = this.req.query[app.get('jsonp callback name')];
277278 // content-type

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 279–282why, one step back
279 if (!this.get('Content-Type')) {
280 this.set('X-Content-Type-Options', 'nosniff');281 this.set('Content-Type', 'application/json');282 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 283why, one step back
283

Merge branch '4.1.x'Douglas Christopher Wilsonbefore adoption0bbbc84

lines 284–288why, one step back
284 // fixup callback
285 if (Array.isArray(callback)) {286 callback = callback[0];287 }288

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 289why, one step back
289 // jsonp

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 290–292why, one step back
290 if (typeof callback === 'string' && callback.length !== 0) {
291 this.charset = 'utf-8';292 this.set('X-Content-Type-Options', 'nosniff');

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 293why, one step back
293 this.set('Content-Type', 'text/javascript');

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

lines 294–305why, one step back
294
295 // 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 + ');';

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 306–321why, one step back
306 }
307308 return this.send(body);309};310311/**312 * Transfer the file at the given `path`.313 *314 * Automatically sets the _Content-Type_ response header field.315 * The callback `fn(err)` is invoked when the transfer is complete316 * or when an error occurs. Be sure to check `res.sentHeader`317 * if you wish to attempt responding, as the header and some data318 * may have already been transferred.319 *320 * Options:321 *

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 322–325why, one step back
322 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
323 * - `root` root directory for relative filenames324 * - `headers` object of headers to serve with file325 * - `hidden` serve hidden files, defaulting to false

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 326why, one step back
326 *

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 327–328why, one step back
327 * Other options are passed along to `send`.
328 *

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 329–352why, one step back
329 * Examples:
330 *331 * The following example illustrates how `res.sendfile()` may332 * be used as an alternative for the `static()` middleware for333 * dynamic situations. The code backing `res.sendfile()` is actually334 * the same code, so HTTP cache support etc is identical.335 *336 * app.get('/user/:uid/photos/:file', function(req, res){337 * var uid = req.params.uid338 * , file = req.params.file;339 *340 * req.user.mayViewFilesFrom(uid, function(yes){341 * if (yes) {342 * res.sendfile('/uploads/' + uid + '/' + file);343 * } else {344 * res.send(403, 'Sorry! you cant see that.');345 * }346 * });347 * });348 *349 * @api public350 */351352res.sendfile = function(path, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 353–357why, one step back
353 options = options || {};
354 var self = this;355 var req = self.req;356 var next = this.req.next;357 var done;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 358why, one step back
358

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

line 359why, one step back
359

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 360–395why, one step back
360 // support function as second arg
361 if ('function' == typeof options) {362 fn = options;363 options = {};364 }365366 // socket errors367 req.socket.on('error', error);368369 // errors370 function error(err) {371 if (done) return;372 done = true;373374 // clean up375 cleanup();376377 // callback available378 if (fn) return fn(err);379380 // delegate381 next(err);382 }383384 // streaming385 function stream(stream) {386 if (done) return;387 cleanup();388 if (fn) stream.on('end', fn);389 }390391 // cleanup392 function cleanup() {393 req.socket.removeListener('error', error);394 }395

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

lines 396–398why, one step back
396 // Back-compat
397 options.maxage = options.maxage || options.maxAge || 0;398

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 399why, one step back
399 // transfer

Pass options from res.sendfile to sendDouglas Christopher Wilsonbefore adoption2fd3e72

line 400why, one step back
400 var file = send(req, path, options);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 401–403why, one step back
401 file.on('error', error);
402 file.on('directory', next);403 file.on('stream', stream);

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 404–418why, one step back
404
405 if (options.headers) {406 // set headers on successful transfer407 file.on('headers', function headers(res) {408 var obj = options.headers;409 var keys = Object.keys(obj);410411 for (var i = 0; i < keys.length; i++) {412 var k = keys[i];413 res.setHeader(k, obj[k]);414 }415 });416 }417418 // pipe

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 419–443why, one step back
419 file.pipe(this);
420 this.on('finish', cleanup);421};422423/**424 * Transfer the file at the given `path` as an attachment.425 *426 * Optionally providing an alternate attachment `filename`,427 * and optional callback `fn(err)`. The callback is invoked428 * when the data transfer is complete, or when an error has429 * ocurred. Be sure to check `res.headersSent` if you plan to respond.430 *431 * This method uses `res.sendfile()`.432 *433 * @api public434 */435436res.download = function(path, filename, fn){437 // support function as second arg438 if ('function' == typeof filename) {439 fn = filename;440 filename = null;441 }442443 filename = filename || path;

Add headers option to res.sendfileDouglas Christopher Wilsonbefore adoptionce3d1fe

lines 444–450why, one step back
444
445 // set Content-Disposition when file is sent446 var headers = {447 'Content-Disposition': contentDisposition(filename)448 };449450 return this.sendfile(path, { headers: headers }, fn);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 451–534why, one step back
451};
452453/**454 * Set _Content-Type_ response header with `type` through `mime.lookup()`455 * when it does not contain "/", or set the Content-Type to `type` otherwise.456 *457 * Examples:458 *459 * res.type('.html');460 * res.type('html');461 * res.type('json');462 * res.type('application/json');463 * res.type('png');464 *465 * @param {String} type466 * @return {ServerResponse} for chaining467 * @api public468 */469470res.contentType =471res.type = function(type){472 return this.set('Content-Type', ~type.indexOf('/')473 ? type474 : mime.lookup(type));475};476477/**478 * Respond to the Acceptable formats using an `obj`479 * of mime-type callbacks.480 *481 * This method uses `req.accepted`, an array of482 * acceptable types ordered by their quality values.483 * When "Accept" is not present the _first_ callback484 * is invoked, otherwise the first match is used. When485 * no match is performed the server responds with486 * 406 "Not Acceptable".487 *488 * Content-Type is set for you, however if you choose489 * you may alter this within the callback using `res.type()`490 * or `res.set('Content-Type', ...)`.491 *492 * res.format({493 * 'text/plain': function(){494 * res.send('hey');495 * },496 *497 * 'text/html': function(){498 * res.send('<p>hey</p>');499 * },500 *501 * 'appliation/json': function(){502 * res.send({ message: 'hey' });503 * }504 * });505 *506 * In addition to canonicalized MIME types you may507 * also use extnames mapped to these types:508 *509 * res.format({510 * text: function(){511 * res.send('hey');512 * },513 *514 * html: function(){515 * res.send('<p>hey</p>');516 * },517 *518 * json: function(){519 * res.send({ message: 'hey' });520 * }521 * });522 *523 * By default Express passes an `Error`524 * with a `.status` of 406 to `next(err)`525 * if a match is not made. If you provide526 * a `.default` callback it will be invoked527 * instead.528 *529 * @param {Object} obj530 * @return {ServerResponse} for chaining531 * @api public532 */533534res.format = function(obj){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 535–536why, one step back
535 var req = this.req;
536 var next = req.next;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 537–546why, one step back
537
538 var fn = obj.default;539 if (fn) delete obj.default;540 var keys = Object.keys(obj);541542 var key = req.accepts(keys);543544 this.vary("Accept");545546 if (key) {

remove res.charset usageJonathan Ongbefore adoption2064f41

line 547why, one step back
547 this.set('Content-Type', normalizeType(key).value);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 548–570why, one step back
548 obj[key](req, this, next);
549 } else if (fn) {550 fn();551 } else {552 var err = new Error('Not Acceptable');553 err.status = 406;554 err.types = normalizeTypes(keys).map(function(o){ return o.value });555 next(err);556 }557558 return this;559};560561/**562 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.563 *564 * @param {String} filename565 * @return {ServerResponse}566 * @api public567 */568569res.attachment = function(filename){570 if (filename) this.type(extname(filename));

Merge pull request #2058 from thetalecrafter/content-dispositionRoman Shtylmanbefore adoptionbdb3bb9

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

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 572–593why, one step back
572 return this;
573};574575/**576 * Set header `field` to `val`, or pass577 * an object of header fields.578 *579 * Examples:580 *581 * res.set('Foo', ['bar', 'baz']);582 * res.set('Accept', 'application/json');583 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });584 *585 * Aliased as `res.header()`.586 *587 * @param {String|Object|Array} field588 * @param {String} val589 * @return {ServerResponse} for chaining590 * @api public591 */592593res.set =

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 594–595why, one step back
594res.header = function header(field, val) {
595 if (arguments.length === 2) {

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 596–597why, one step back
596 if (Array.isArray(val)) val = val.map(String);
597 else val = String(val);

preserve casing of headers in res.header and res.setDouglas Christopher Wilsonbefore adoption1536a21

line 598why, one step back
598 if ('content-type' == field.toLowerCase() && !/;\s*charset\s*=/.test(val)) {

move setHeader charset patch to .setJonathan Ongbefore adoptionbad55f7

lines 599–601why, one step back
599 var charset = mime.charsets.lookup(val.split(';')[0]);
600 if (charset) val += '; charset=' + charset.toLowerCase();601 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 602–627why, one step back
602 this.setHeader(field, val);
603 } else {604 for (var key in field) {605 this.set(key, field[key]);606 }607 }608 return this;609};610611/**612 * Get value for header `field`.613 *614 * @param {String} field615 * @return {String}616 * @api public617 */618619res.get = function(field){620 return this.getHeader(field);621};622623/**624 * Clear cookie `name`.625 *626 * @param {String} name627 * @param {Object} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

line 628why, one step back
628 * @return {ServerResponse} for chaining

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 629–658why, one step back
629 * @api public
630 */631632res.clearCookie = function(name, options){633 var opts = { expires: new Date(1), path: '/' };634 return this.cookie(name, '', options635 ? mixin(opts, options)636 : opts);637};638639/**640 * Set cookie `name` to `val`, with the given `options`.641 *642 * Options:643 *644 * - `maxAge` max-age in milliseconds, converted to `expires`645 * - `signed` sign the cookie646 * - `path` defaults to "/"647 *648 * Examples:649 *650 * // "Remember Me" for 15 minutes651 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });652 *653 * // save as above654 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })655 *656 * @param {String} name657 * @param {String|Object} val658 * @param {Options} options

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

line 659why, one step back
659 * @return {ServerResponse} for chaining

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 660–704why, one step back
660 * @api public
661 */662663res.cookie = function(name, val, options){664 options = mixin({}, options);665 var secret = this.req.secret;666 var signed = options.signed;667 if (signed && !secret) throw new Error('cookieParser("secret") required for signed cookies');668 if ('number' == typeof val) val = val.toString();669 if ('object' == typeof val) val = 'j:' + JSON.stringify(val);670 if (signed) val = 's:' + sign(val, secret);671 if ('maxAge' in options) {672 options.expires = new Date(Date.now() + options.maxAge);673 options.maxAge /= 1000;674 }675 if (null == options.path) options.path = '/';676 var headerVal = cookie.serialize(name, String(val), options);677678 // supports multiple 'res.cookie' calls by getting previous value679 var prev = this.get('Set-Cookie');680 if (prev) {681 if (Array.isArray(prev)) {682 headerVal = prev.concat(headerVal);683 } else {684 headerVal = [prev, headerVal];685 }686 }687 this.set('Set-Cookie', headerVal);688 return this;689};690691692/**693 * Set the location header to `url`.694 *695 * The given `url` can also be "back", which redirects696 * to the _Referrer_ or _Referer_ headers or "/".697 *698 * Examples:699 *700 * res.location('/foo/bar').;701 * res.location('http://example.com');702 * res.location('../login');703 *704 * @param {String} url

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

line 705why, one step back
705 * @return {ServerResponse} for chaining

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 706–737why, one step back
706 * @api public
707 */708709res.location = function(url){710 var req = this.req;711712 // "back" is an alias for the referrer713 if ('back' == url) url = req.get('Referrer') || '/';714715 // Respond716 this.set('Location', url);717 return this;718};719720/**721 * Redirect to the given `url` with optional response `status`722 * defaulting to 302.723 *724 * The resulting `url` is determined by `res.location()`, so725 * it will play nicely with mounted apps, relative paths,726 * `"back"` etc.727 *728 * Examples:729 *730 * res.redirect('/foo/bar');731 * res.redirect('http://example.com');732 * res.redirect(301, 'http://example.com');733 * res.redirect('../login'); // /blog/post/1 -> /blog/login734 *735 * @api public736 */737

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 738–739why, one step back
738res.redirect = function redirect(url) {
739 var address = url;

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

line 740why, one step back
740 var body;

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

line 741why, one step back
741 var status = 302;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 742–743why, one step back
742
743 // allow status / url

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 744–747why, one step back
744 if (arguments.length === 2) {
745 if (typeof arguments[0] === 'number') {746 status = arguments[0];747 address = arguments[1];

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 748why, one step back
748 } else {

Merge tag '3.14.0'Douglas Christopher Wilsonbefore adoption4ea6f21

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

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 750–754why, one step back
750 status = arguments[1];
751 }752 }753754 // Set location header

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 755–756why, one step back
755 this.location(address);
756 address = this.get('Location');

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 757–776why, one step back
757
758 // Support text/{plain,html} by default759 this.format({760 text: function(){761 body = statusCodes[status] + '. Redirecting to ' + encodeURI(url);762 },763764 html: function(){765 var u = escapeHtml(url);766 body = '<p>' + statusCodes[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>';767 },768769 default: function(){770 body = '';771 }772 });773774 // Respond775 this.statusCode = status;776 this.set('Content-Length', Buffer.byteLength(body));

perf: fix arguments reassign deopt in some res methodsDouglas Christopher Wilsonbefore adoptionc6e6203

lines 777–782why, one step back
777
778 if (this.req.method === 'HEAD') {779 this.end();780 }781782 this.end(body);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 783–789why, one step back
783};
784785/**786 * Add `field` to Vary. If already present in the Vary set, then787 * this call is simply ignored.788 *789 * @param {Array|String} field

build: fix up jsdoc return valuesVasilyev Dmitrybefore adoptionfd86ab8

line 790why, one step back
790 * @return {ServerResponse} for chaining

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 791–794why, one step back
791 * @api public
792 */793794res.vary = function(field){

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 795why, one step back
795 // checks for back-compat

add deprecation message to res.vary()Douglas Christopher Wilsonbefore adoption381b3b0

lines 796–799why, one step back
796 if (!field || (Array.isArray(field) && !field.length)) {
797 deprecate('res.vary(): Provide a field name');798 return this;799 }

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

line 800why, one step back
800

Merge tag '3.10.3'Douglas Christopher Wilsonbefore adoption9bf1247

line 801why, one step back
801 vary(this, field);

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 802–819why, one step back
802
803 return this;804};805806/**807 * Render `view` with the given `options` and optional callback `fn`.808 * When a callback function is given a response will _not_ be made809 * automatically, otherwise a response of _200_ and _text/html_ is given.810 *811 * Options:812 *813 * - `cache` boolean hinting to the engine it should cache814 * - `filename` filename of the view being rendered815 *816 * @api public817 */818819res.render = function(view, options, fn){

Merge pull request #2004 from agchou/clean-up-codeJonathan Ongbefore adoption0120874

lines 820–823why, one step back
820 options = options || {};
821 var self = this;822 var req = this.req;823 var app = req.app;

4.0.0-rc1Roman Shtylmanbefore adoption9df1067

lines 824–841why, one step back
824
825 // support callback function as second arg826 if ('function' == typeof options) {827 fn = options, options = {};828 }829830 // merge res.locals831 options._locals = self.locals;832833 // default callback to respond834 fn = fn || function(err, str){835 if (err) return req.next(err);836 self.send(str);837 };838839 // render840 app.render(view, options, fn);841};