response.js 24 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /*!
  2. * express
  3. * Copyright(c) 2009-2013 TJ Holowaychuk
  4. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  5. * MIT Licensed
  6. */
  7. 'use strict';
  8. /**
  9. * Module dependencies.
  10. * @private
  11. */
  12. var contentDisposition = require('content-disposition');
  13. var createError = require('http-errors')
  14. var encodeUrl = require('encodeurl');
  15. var escapeHtml = require('escape-html');
  16. var http = require('node:http');
  17. var onFinished = require('on-finished');
  18. var mime = require('mime-types')
  19. var path = require('node:path');
  20. var pathIsAbsolute = require('node:path').isAbsolute;
  21. var statuses = require('statuses')
  22. var sign = require('cookie-signature').sign;
  23. var normalizeType = require('./utils').normalizeType;
  24. var normalizeTypes = require('./utils').normalizeTypes;
  25. var setCharset = require('./utils').setCharset;
  26. var cookie = require('cookie');
  27. var send = require('send');
  28. var extname = path.extname;
  29. var resolve = path.resolve;
  30. var vary = require('vary');
  31. /**
  32. * Response prototype.
  33. * @public
  34. */
  35. var res = Object.create(http.ServerResponse.prototype)
  36. /**
  37. * Module exports.
  38. * @public
  39. */
  40. module.exports = res
  41. /**
  42. * Set the HTTP status code for the response.
  43. *
  44. * Expects an integer value between 100 and 999 inclusive.
  45. * Throws an error if the provided status code is not an integer or if it's outside the allowable range.
  46. *
  47. * @param {number} code - The HTTP status code to set.
  48. * @return {ServerResponse} - Returns itself for chaining methods.
  49. * @throws {TypeError} If `code` is not an integer.
  50. * @throws {RangeError} If `code` is outside the range 100 to 999.
  51. * @public
  52. */
  53. res.status = function status(code) {
  54. // Check if the status code is not an integer
  55. if (!Number.isInteger(code)) {
  56. throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);
  57. }
  58. // Check if the status code is outside of Node's valid range
  59. if (code < 100 || code > 999) {
  60. throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);
  61. }
  62. this.statusCode = code;
  63. return this;
  64. };
  65. /**
  66. * Set Link header field with the given `links`.
  67. *
  68. * Examples:
  69. *
  70. * res.links({
  71. * next: 'http://api.example.com/users?page=2',
  72. * last: 'http://api.example.com/users?page=5',
  73. * pages: [
  74. * 'http://api.example.com/users?page=1',
  75. * 'http://api.example.com/users?page=2'
  76. * ]
  77. * });
  78. *
  79. * @param {Object} links
  80. * @return {ServerResponse}
  81. * @public
  82. */
  83. res.links = function(links) {
  84. var link = this.get('Link') || '';
  85. if (link) link += ', ';
  86. return this.set('Link', link + Object.keys(links).map(function(rel) {
  87. // Allow multiple links if links[rel] is an array
  88. if (Array.isArray(links[rel])) {
  89. return links[rel].map(function (singleLink) {
  90. return `<${singleLink}>; rel="${rel}"`;
  91. }).join(', ');
  92. } else {
  93. return `<${links[rel]}>; rel="${rel}"`;
  94. }
  95. }).join(', '));
  96. };
  97. /**
  98. * Send a response.
  99. *
  100. * Examples:
  101. *
  102. * res.send(Buffer.from('wahoo'));
  103. * res.send({ some: 'json' });
  104. * res.send('<p>some html</p>');
  105. *
  106. * @param {string|number|boolean|object|Buffer} body
  107. * @public
  108. */
  109. res.send = function send(body) {
  110. var chunk = body;
  111. var encoding;
  112. var req = this.req;
  113. var type;
  114. // settings
  115. var app = this.app;
  116. switch (typeof chunk) {
  117. // string defaulting to html
  118. case 'string':
  119. if (!this.get('Content-Type')) {
  120. this.type('html');
  121. }
  122. break;
  123. case 'boolean':
  124. case 'number':
  125. case 'object':
  126. if (chunk === null) {
  127. chunk = '';
  128. } else if (ArrayBuffer.isView(chunk)) {
  129. if (!this.get('Content-Type')) {
  130. this.type('bin');
  131. }
  132. } else {
  133. return this.json(chunk);
  134. }
  135. break;
  136. }
  137. // write strings in utf-8
  138. if (typeof chunk === 'string') {
  139. encoding = 'utf8';
  140. type = this.get('Content-Type');
  141. // reflect this in content-type
  142. if (typeof type === 'string') {
  143. this.set('Content-Type', setCharset(type, 'utf-8'));
  144. }
  145. }
  146. // determine if ETag should be generated
  147. var etagFn = app.get('etag fn')
  148. var generateETag = !this.get('ETag') && typeof etagFn === 'function'
  149. // populate Content-Length
  150. var len
  151. if (chunk !== undefined) {
  152. if (Buffer.isBuffer(chunk)) {
  153. // get length of Buffer
  154. len = chunk.length
  155. } else if (!generateETag && chunk.length < 1000) {
  156. // just calculate length when no ETag + small chunk
  157. len = Buffer.byteLength(chunk, encoding)
  158. } else {
  159. // convert chunk to Buffer and calculate
  160. chunk = Buffer.from(chunk, encoding)
  161. encoding = undefined;
  162. len = chunk.length
  163. }
  164. this.set('Content-Length', len);
  165. }
  166. // populate ETag
  167. var etag;
  168. if (generateETag && len !== undefined) {
  169. if ((etag = etagFn(chunk, encoding))) {
  170. this.set('ETag', etag);
  171. }
  172. }
  173. // freshness
  174. if (req.fresh) this.status(304);
  175. // strip irrelevant headers
  176. if (204 === this.statusCode || 304 === this.statusCode) {
  177. this.removeHeader('Content-Type');
  178. this.removeHeader('Content-Length');
  179. this.removeHeader('Transfer-Encoding');
  180. chunk = '';
  181. }
  182. // alter headers for 205
  183. if (this.statusCode === 205) {
  184. this.set('Content-Length', '0')
  185. this.removeHeader('Transfer-Encoding')
  186. chunk = ''
  187. }
  188. if (req.method === 'HEAD') {
  189. // skip body for HEAD
  190. this.end();
  191. } else {
  192. // respond
  193. this.end(chunk, encoding);
  194. }
  195. return this;
  196. };
  197. /**
  198. * Send JSON response.
  199. *
  200. * Examples:
  201. *
  202. * res.json(null);
  203. * res.json({ user: 'tj' });
  204. *
  205. * @param {string|number|boolean|object} obj
  206. * @public
  207. */
  208. res.json = function json(obj) {
  209. // settings
  210. var app = this.app;
  211. var escape = app.get('json escape')
  212. var replacer = app.get('json replacer');
  213. var spaces = app.get('json spaces');
  214. var body = stringify(obj, replacer, spaces, escape)
  215. // content-type
  216. if (!this.get('Content-Type')) {
  217. this.set('Content-Type', 'application/json');
  218. }
  219. return this.send(body);
  220. };
  221. /**
  222. * Send JSON response with JSONP callback support.
  223. *
  224. * Examples:
  225. *
  226. * res.jsonp(null);
  227. * res.jsonp({ user: 'tj' });
  228. *
  229. * @param {string|number|boolean|object} obj
  230. * @public
  231. */
  232. res.jsonp = function jsonp(obj) {
  233. // settings
  234. var app = this.app;
  235. var escape = app.get('json escape')
  236. var replacer = app.get('json replacer');
  237. var spaces = app.get('json spaces');
  238. var body = stringify(obj, replacer, spaces, escape)
  239. var callback = this.req.query[app.get('jsonp callback name')];
  240. // content-type
  241. if (!this.get('Content-Type')) {
  242. this.set('X-Content-Type-Options', 'nosniff');
  243. this.set('Content-Type', 'application/json');
  244. }
  245. // fixup callback
  246. if (Array.isArray(callback)) {
  247. callback = callback[0];
  248. }
  249. // jsonp
  250. if (typeof callback === 'string' && callback.length !== 0) {
  251. this.set('X-Content-Type-Options', 'nosniff');
  252. this.set('Content-Type', 'text/javascript');
  253. // restrict callback charset
  254. callback = callback.replace(/[^\[\]\w$.]/g, '');
  255. if (body === undefined) {
  256. // empty argument
  257. body = ''
  258. } else if (typeof body === 'string') {
  259. // replace chars not allowed in JavaScript that are in JSON
  260. body = body
  261. .replace(/\u2028/g, '\\u2028')
  262. .replace(/\u2029/g, '\\u2029')
  263. }
  264. // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
  265. // the typeof check is just to reduce client error noise
  266. body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
  267. }
  268. return this.send(body);
  269. };
  270. /**
  271. * Send given HTTP status code.
  272. *
  273. * Sets the response status to `statusCode` and the body of the
  274. * response to the standard description from node's http.STATUS_CODES
  275. * or the statusCode number if no description.
  276. *
  277. * Examples:
  278. *
  279. * res.sendStatus(200);
  280. *
  281. * @param {number} statusCode
  282. * @public
  283. */
  284. res.sendStatus = function sendStatus(statusCode) {
  285. var body = statuses.message[statusCode] || String(statusCode)
  286. this.status(statusCode);
  287. this.type('txt');
  288. return this.send(body);
  289. };
  290. /**
  291. * Transfer the file at the given `path`.
  292. *
  293. * Automatically sets the _Content-Type_ response header field.
  294. * The callback `callback(err)` is invoked when the transfer is complete
  295. * or when an error occurs. Be sure to check `res.headersSent`
  296. * if you wish to attempt responding, as the header and some data
  297. * may have already been transferred.
  298. *
  299. * Options:
  300. *
  301. * - `maxAge` defaulting to 0 (can be string converted by `ms`)
  302. * - `root` root directory for relative filenames
  303. * - `headers` object of headers to serve with file
  304. * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
  305. *
  306. * Other options are passed along to `send`.
  307. *
  308. * Examples:
  309. *
  310. * The following example illustrates how `res.sendFile()` may
  311. * be used as an alternative for the `static()` middleware for
  312. * dynamic situations. The code backing `res.sendFile()` is actually
  313. * the same code, so HTTP cache support etc is identical.
  314. *
  315. * app.get('/user/:uid/photos/:file', function(req, res){
  316. * var uid = req.params.uid
  317. * , file = req.params.file;
  318. *
  319. * req.user.mayViewFilesFrom(uid, function(yes){
  320. * if (yes) {
  321. * res.sendFile('/uploads/' + uid + '/' + file);
  322. * } else {
  323. * res.send(403, 'Sorry! you cant see that.');
  324. * }
  325. * });
  326. * });
  327. *
  328. * @public
  329. */
  330. res.sendFile = function sendFile(path, options, callback) {
  331. var done = callback;
  332. var req = this.req;
  333. var res = this;
  334. var next = req.next;
  335. var opts = options || {};
  336. if (!path) {
  337. throw new TypeError('path argument is required to res.sendFile');
  338. }
  339. if (typeof path !== 'string') {
  340. throw new TypeError('path must be a string to res.sendFile')
  341. }
  342. // support function as second arg
  343. if (typeof options === 'function') {
  344. done = options;
  345. opts = {};
  346. }
  347. if (!opts.root && !pathIsAbsolute(path)) {
  348. throw new TypeError('path must be absolute or specify root to res.sendFile');
  349. }
  350. // create file stream
  351. var pathname = encodeURI(path);
  352. // wire application etag option to send
  353. opts.etag = this.app.enabled('etag');
  354. var file = send(req, pathname, opts);
  355. // transfer
  356. sendfile(res, file, opts, function (err) {
  357. if (done) return done(err);
  358. if (err && err.code === 'EISDIR') return next();
  359. // next() all but write errors
  360. if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
  361. next(err);
  362. }
  363. });
  364. };
  365. /**
  366. * Transfer the file at the given `path` as an attachment.
  367. *
  368. * Optionally providing an alternate attachment `filename`,
  369. * and optional callback `callback(err)`. The callback is invoked
  370. * when the data transfer is complete, or when an error has
  371. * occurred. Be sure to check `res.headersSent` if you plan to respond.
  372. *
  373. * Optionally providing an `options` object to use with `res.sendFile()`.
  374. * This function will set the `Content-Disposition` header, overriding
  375. * any `Content-Disposition` header passed as header options in order
  376. * to set the attachment and filename.
  377. *
  378. * This method uses `res.sendFile()`.
  379. *
  380. * @public
  381. */
  382. res.download = function download (path, filename, options, callback) {
  383. var done = callback;
  384. var name = filename;
  385. var opts = options || null
  386. // support function as second or third arg
  387. if (typeof filename === 'function') {
  388. done = filename;
  389. name = null;
  390. opts = null
  391. } else if (typeof options === 'function') {
  392. done = options
  393. opts = null
  394. }
  395. // support optional filename, where options may be in it's place
  396. if (typeof filename === 'object' &&
  397. (typeof options === 'function' || options === undefined)) {
  398. name = null
  399. opts = filename
  400. }
  401. // set Content-Disposition when file is sent
  402. var headers = {
  403. 'Content-Disposition': contentDisposition(name || path)
  404. };
  405. // merge user-provided headers
  406. if (opts && opts.headers) {
  407. var keys = Object.keys(opts.headers)
  408. for (var i = 0; i < keys.length; i++) {
  409. var key = keys[i]
  410. if (key.toLowerCase() !== 'content-disposition') {
  411. headers[key] = opts.headers[key]
  412. }
  413. }
  414. }
  415. // merge user-provided options
  416. opts = Object.create(opts)
  417. opts.headers = headers
  418. // Resolve the full path for sendFile
  419. var fullPath = !opts.root
  420. ? resolve(path)
  421. : path
  422. // send file
  423. return this.sendFile(fullPath, opts, done)
  424. };
  425. /**
  426. * Set _Content-Type_ response header with `type` through `mime.contentType()`
  427. * when it does not contain "/", or set the Content-Type to `type` otherwise.
  428. * When no mapping is found though `mime.contentType()`, the type is set to
  429. * "application/octet-stream".
  430. *
  431. * Examples:
  432. *
  433. * res.type('.html');
  434. * res.type('html');
  435. * res.type('json');
  436. * res.type('application/json');
  437. * res.type('png');
  438. *
  439. * @param {String} type
  440. * @return {ServerResponse} for chaining
  441. * @public
  442. */
  443. res.contentType =
  444. res.type = function contentType(type) {
  445. var ct = type.indexOf('/') === -1
  446. ? (mime.contentType(type) || 'application/octet-stream')
  447. : type;
  448. return this.set('Content-Type', ct);
  449. };
  450. /**
  451. * Respond to the Acceptable formats using an `obj`
  452. * of mime-type callbacks.
  453. *
  454. * This method uses `req.accepted`, an array of
  455. * acceptable types ordered by their quality values.
  456. * When "Accept" is not present the _first_ callback
  457. * is invoked, otherwise the first match is used. When
  458. * no match is performed the server responds with
  459. * 406 "Not Acceptable".
  460. *
  461. * Content-Type is set for you, however if you choose
  462. * you may alter this within the callback using `res.type()`
  463. * or `res.set('Content-Type', ...)`.
  464. *
  465. * res.format({
  466. * 'text/plain': function(){
  467. * res.send('hey');
  468. * },
  469. *
  470. * 'text/html': function(){
  471. * res.send('<p>hey</p>');
  472. * },
  473. *
  474. * 'application/json': function () {
  475. * res.send({ message: 'hey' });
  476. * }
  477. * });
  478. *
  479. * In addition to canonicalized MIME types you may
  480. * also use extnames mapped to these types:
  481. *
  482. * res.format({
  483. * text: function(){
  484. * res.send('hey');
  485. * },
  486. *
  487. * html: function(){
  488. * res.send('<p>hey</p>');
  489. * },
  490. *
  491. * json: function(){
  492. * res.send({ message: 'hey' });
  493. * }
  494. * });
  495. *
  496. * By default Express passes an `Error`
  497. * with a `.status` of 406 to `next(err)`
  498. * if a match is not made. If you provide
  499. * a `.default` callback it will be invoked
  500. * instead.
  501. *
  502. * @param {Object} obj
  503. * @return {ServerResponse} for chaining
  504. * @public
  505. */
  506. res.format = function(obj){
  507. var req = this.req;
  508. var next = req.next;
  509. var keys = Object.keys(obj)
  510. .filter(function (v) { return v !== 'default' })
  511. var key = keys.length > 0
  512. ? req.accepts(keys)
  513. : false;
  514. this.vary("Accept");
  515. if (key) {
  516. this.set('Content-Type', normalizeType(key).value);
  517. obj[key](req, this, next);
  518. } else if (obj.default) {
  519. obj.default(req, this, next)
  520. } else {
  521. next(createError(406, {
  522. types: normalizeTypes(keys).map(function (o) { return o.value })
  523. }))
  524. }
  525. return this;
  526. };
  527. /**
  528. * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
  529. *
  530. * @param {String} filename
  531. * @return {ServerResponse}
  532. * @public
  533. */
  534. res.attachment = function attachment(filename) {
  535. if (filename) {
  536. this.type(extname(filename));
  537. }
  538. this.set('Content-Disposition', contentDisposition(filename));
  539. return this;
  540. };
  541. /**
  542. * Append additional header `field` with value `val`.
  543. *
  544. * Example:
  545. *
  546. * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
  547. * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
  548. * res.append('Warning', '199 Miscellaneous warning');
  549. *
  550. * @param {String} field
  551. * @param {String|Array} val
  552. * @return {ServerResponse} for chaining
  553. * @public
  554. */
  555. res.append = function append(field, val) {
  556. var prev = this.get(field);
  557. var value = val;
  558. if (prev) {
  559. // concat the new and prev vals
  560. value = Array.isArray(prev) ? prev.concat(val)
  561. : Array.isArray(val) ? [prev].concat(val)
  562. : [prev, val]
  563. }
  564. return this.set(field, value);
  565. };
  566. /**
  567. * Set header `field` to `val`, or pass
  568. * an object of header fields.
  569. *
  570. * Examples:
  571. *
  572. * res.set('Foo', ['bar', 'baz']);
  573. * res.set('Accept', 'application/json');
  574. * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
  575. *
  576. * Aliased as `res.header()`.
  577. *
  578. * When the set header is "Content-Type", the type is expanded to include
  579. * the charset if not present using `mime.contentType()`.
  580. *
  581. * @param {String|Object} field
  582. * @param {String|Array} val
  583. * @return {ServerResponse} for chaining
  584. * @public
  585. */
  586. res.set =
  587. res.header = function header(field, val) {
  588. if (arguments.length === 2) {
  589. var value = Array.isArray(val)
  590. ? val.map(String)
  591. : String(val);
  592. // add charset to content-type
  593. if (field.toLowerCase() === 'content-type') {
  594. if (Array.isArray(value)) {
  595. throw new TypeError('Content-Type cannot be set to an Array');
  596. }
  597. value = mime.contentType(value)
  598. }
  599. this.setHeader(field, value);
  600. } else {
  601. for (var key in field) {
  602. this.set(key, field[key]);
  603. }
  604. }
  605. return this;
  606. };
  607. /**
  608. * Get value for header `field`.
  609. *
  610. * @param {String} field
  611. * @return {String}
  612. * @public
  613. */
  614. res.get = function(field){
  615. return this.getHeader(field);
  616. };
  617. /**
  618. * Clear cookie `name`.
  619. *
  620. * @param {String} name
  621. * @param {Object} [options]
  622. * @return {ServerResponse} for chaining
  623. * @public
  624. */
  625. res.clearCookie = function clearCookie(name, options) {
  626. // Force cookie expiration by setting expires to the past
  627. const opts = { path: '/', ...options, expires: new Date(1)};
  628. // ensure maxAge is not passed
  629. delete opts.maxAge
  630. return this.cookie(name, '', opts);
  631. };
  632. /**
  633. * Set cookie `name` to `value`, with the given `options`.
  634. *
  635. * Options:
  636. *
  637. * - `maxAge` max-age in milliseconds, converted to `expires`
  638. * - `signed` sign the cookie
  639. * - `path` defaults to "/"
  640. *
  641. * Examples:
  642. *
  643. * // "Remember Me" for 15 minutes
  644. * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
  645. *
  646. * // same as above
  647. * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
  648. *
  649. * @param {String} name
  650. * @param {String|Object} value
  651. * @param {Object} [options]
  652. * @return {ServerResponse} for chaining
  653. * @public
  654. */
  655. res.cookie = function (name, value, options) {
  656. var opts = { ...options };
  657. var secret = this.req.secret;
  658. var signed = opts.signed;
  659. if (signed && !secret) {
  660. throw new Error('cookieParser("secret") required for signed cookies');
  661. }
  662. var val = typeof value === 'object'
  663. ? 'j:' + JSON.stringify(value)
  664. : String(value);
  665. if (signed) {
  666. val = 's:' + sign(val, secret);
  667. }
  668. if (opts.maxAge != null) {
  669. var maxAge = opts.maxAge - 0
  670. if (!isNaN(maxAge)) {
  671. opts.expires = new Date(Date.now() + maxAge)
  672. opts.maxAge = Math.floor(maxAge / 1000)
  673. }
  674. }
  675. if (opts.path == null) {
  676. opts.path = '/';
  677. }
  678. this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
  679. return this;
  680. };
  681. /**
  682. * Set the location header to `url`.
  683. *
  684. * The given `url` can also be "back", which redirects
  685. * to the _Referrer_ or _Referer_ headers or "/".
  686. *
  687. * Examples:
  688. *
  689. * res.location('/foo/bar').;
  690. * res.location('http://example.com');
  691. * res.location('../login');
  692. *
  693. * @param {String} url
  694. * @return {ServerResponse} for chaining
  695. * @public
  696. */
  697. res.location = function location(url) {
  698. return this.set('Location', encodeUrl(url));
  699. };
  700. /**
  701. * Redirect to the given `url` with optional response `status`
  702. * defaulting to 302.
  703. *
  704. * Examples:
  705. *
  706. * res.redirect('/foo/bar');
  707. * res.redirect('http://example.com');
  708. * res.redirect(301, 'http://example.com');
  709. * res.redirect('../login'); // /blog/post/1 -> /blog/login
  710. *
  711. * @public
  712. */
  713. res.redirect = function redirect(url) {
  714. var address = url;
  715. var body;
  716. var status = 302;
  717. // allow status / url
  718. if (arguments.length === 2) {
  719. status = arguments[0]
  720. address = arguments[1]
  721. }
  722. // Set location header
  723. address = this.location(address).get('Location');
  724. // Support text/{plain,html} by default
  725. this.format({
  726. text: function(){
  727. body = statuses.message[status] + '. Redirecting to ' + address
  728. },
  729. html: function(){
  730. var u = escapeHtml(address);
  731. body = '<p>' + statuses.message[status] + '. Redirecting to ' + u + '</p>'
  732. },
  733. default: function(){
  734. body = '';
  735. }
  736. });
  737. // Respond
  738. this.status(status);
  739. this.set('Content-Length', Buffer.byteLength(body));
  740. if (this.req.method === 'HEAD') {
  741. this.end();
  742. } else {
  743. this.end(body);
  744. }
  745. };
  746. /**
  747. * Add `field` to Vary. If already present in the Vary set, then
  748. * this call is simply ignored.
  749. *
  750. * @param {Array|String} field
  751. * @return {ServerResponse} for chaining
  752. * @public
  753. */
  754. res.vary = function(field){
  755. vary(this, field);
  756. return this;
  757. };
  758. /**
  759. * Render `view` with the given `options` and optional callback `fn`.
  760. * When a callback function is given a response will _not_ be made
  761. * automatically, otherwise a response of _200_ and _text/html_ is given.
  762. *
  763. * Options:
  764. *
  765. * - `cache` boolean hinting to the engine it should cache
  766. * - `filename` filename of the view being rendered
  767. *
  768. * @public
  769. */
  770. res.render = function render(view, options, callback) {
  771. var app = this.req.app;
  772. var done = callback;
  773. var opts = options || {};
  774. var req = this.req;
  775. var self = this;
  776. // support callback function as second arg
  777. if (typeof options === 'function') {
  778. done = options;
  779. opts = {};
  780. }
  781. // merge res.locals
  782. opts._locals = self.locals;
  783. // default callback to respond
  784. done = done || function (err, str) {
  785. if (err) return req.next(err);
  786. self.send(str);
  787. };
  788. // render
  789. app.render(view, opts, done);
  790. };
  791. // pipe the send file stream
  792. function sendfile(res, file, options, callback) {
  793. var done = false;
  794. var streaming;
  795. // request aborted
  796. function onaborted() {
  797. if (done) return;
  798. done = true;
  799. var err = new Error('Request aborted');
  800. err.code = 'ECONNABORTED';
  801. callback(err);
  802. }
  803. // directory
  804. function ondirectory() {
  805. if (done) return;
  806. done = true;
  807. var err = new Error('EISDIR, read');
  808. err.code = 'EISDIR';
  809. callback(err);
  810. }
  811. // errors
  812. function onerror(err) {
  813. if (done) return;
  814. done = true;
  815. callback(err);
  816. }
  817. // ended
  818. function onend() {
  819. if (done) return;
  820. done = true;
  821. callback();
  822. }
  823. // file
  824. function onfile() {
  825. streaming = false;
  826. }
  827. // finished
  828. function onfinish(err) {
  829. if (err && err.code === 'ECONNRESET') return onaborted();
  830. if (err) return onerror(err);
  831. if (done) return;
  832. setImmediate(function () {
  833. if (streaming !== false && !done) {
  834. onaborted();
  835. return;
  836. }
  837. if (done) return;
  838. done = true;
  839. callback();
  840. });
  841. }
  842. // streaming
  843. function onstream() {
  844. streaming = true;
  845. }
  846. file.on('directory', ondirectory);
  847. file.on('end', onend);
  848. file.on('error', onerror);
  849. file.on('file', onfile);
  850. file.on('stream', onstream);
  851. onFinished(res, onfinish);
  852. if (options.headers) {
  853. // set headers on successful transfer
  854. file.on('headers', function headers(res) {
  855. var obj = options.headers;
  856. var keys = Object.keys(obj);
  857. for (var i = 0; i < keys.length; i++) {
  858. var k = keys[i];
  859. res.setHeader(k, obj[k]);
  860. }
  861. });
  862. }
  863. // pipe
  864. file.pipe(res);
  865. }
  866. /**
  867. * Stringify JSON, like JSON.stringify, but v8 optimized, with the
  868. * ability to escape characters that can trigger HTML sniffing.
  869. *
  870. * @param {*} value
  871. * @param {function} replacer
  872. * @param {number} spaces
  873. * @param {boolean} escape
  874. * @returns {string}
  875. * @private
  876. */
  877. function stringify (value, replacer, spaces, escape) {
  878. // v8 checks arguments.length for optimizing simple call
  879. // https://bugs.chromium.org/p/v8/issues/detail?id=4730
  880. var json = replacer || spaces
  881. ? JSON.stringify(value, replacer, spaces)
  882. : JSON.stringify(value);
  883. if (escape && typeof json === 'string') {
  884. json = json.replace(/[<>&]/g, function (c) {
  885. switch (c.charCodeAt(0)) {
  886. case 0x3c:
  887. return '\\u003c'
  888. case 0x3e:
  889. return '\\u003e'
  890. case 0x26:
  891. return '\\u0026'
  892. /* istanbul ignore next: unreachable default */
  893. default:
  894. return c
  895. }
  896. })
  897. }
  898. return json
  899. }