response.js 26 KB

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