response.js 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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. if (typeof path !== 'string') {
  360. throw new TypeError('path must be a string to res.sendFile')
  361. }
  362. // support function as second arg
  363. if (typeof options === 'function') {
  364. done = options;
  365. opts = {};
  366. }
  367. if (!opts.root && !isAbsolute(path)) {
  368. throw new TypeError('path must be absolute or specify root to res.sendFile');
  369. }
  370. // create file stream
  371. var pathname = encodeURI(path);
  372. var file = send(req, pathname, opts);
  373. // transfer
  374. sendfile(res, file, opts, function (err) {
  375. if (done) return done(err);
  376. if (err && err.code === 'EISDIR') return next();
  377. // next() all but write errors
  378. if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
  379. next(err);
  380. }
  381. });
  382. };
  383. /**
  384. * Transfer the file at the given `path`.
  385. *
  386. * Automatically sets the _Content-Type_ response header field.
  387. * The callback `callback(err)` is invoked when the transfer is complete
  388. * or when an error occurs. Be sure to check `res.sentHeader`
  389. * if you wish to attempt responding, as the header and some data
  390. * may have already been transferred.
  391. *
  392. * Options:
  393. *
  394. * - `maxAge` defaulting to 0 (can be string converted by `ms`)
  395. * - `root` root directory for relative filenames
  396. * - `headers` object of headers to serve with file
  397. * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
  398. *
  399. * Other options are passed along to `send`.
  400. *
  401. * Examples:
  402. *
  403. * The following example illustrates how `res.sendfile()` may
  404. * be used as an alternative for the `static()` middleware for
  405. * dynamic situations. The code backing `res.sendfile()` is actually
  406. * the same code, so HTTP cache support etc is identical.
  407. *
  408. * app.get('/user/:uid/photos/:file', function(req, res){
  409. * var uid = req.params.uid
  410. * , file = req.params.file;
  411. *
  412. * req.user.mayViewFilesFrom(uid, function(yes){
  413. * if (yes) {
  414. * res.sendfile('/uploads/' + uid + '/' + file);
  415. * } else {
  416. * res.send(403, 'Sorry! you cant see that.');
  417. * }
  418. * });
  419. * });
  420. *
  421. * @public
  422. */
  423. res.sendfile = function (path, options, callback) {
  424. var done = callback;
  425. var req = this.req;
  426. var res = this;
  427. var next = req.next;
  428. var opts = options || {};
  429. // support function as second arg
  430. if (typeof options === 'function') {
  431. done = options;
  432. opts = {};
  433. }
  434. // create file stream
  435. var file = send(req, path, opts);
  436. // transfer
  437. sendfile(res, file, opts, function (err) {
  438. if (done) return done(err);
  439. if (err && err.code === 'EISDIR') return next();
  440. // next() all but write errors
  441. if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
  442. next(err);
  443. }
  444. });
  445. };
  446. res.sendfile = deprecate.function(res.sendfile,
  447. 'res.sendfile: Use res.sendFile instead');
  448. /**
  449. * Transfer the file at the given `path` as an attachment.
  450. *
  451. * Optionally providing an alternate attachment `filename`,
  452. * and optional callback `callback(err)`. The callback is invoked
  453. * when the data transfer is complete, or when an error has
  454. * ocurred. Be sure to check `res.headersSent` if you plan to respond.
  455. *
  456. * Optionally providing an `options` object to use with `res.sendFile()`.
  457. * This function will set the `Content-Disposition` header, overriding
  458. * any `Content-Disposition` header passed as header options in order
  459. * to set the attachment and filename.
  460. *
  461. * This method uses `res.sendFile()`.
  462. *
  463. * @public
  464. */
  465. res.download = function download (path, filename, options, callback) {
  466. var done = callback;
  467. var name = filename;
  468. var opts = options || null
  469. // support function as second or third arg
  470. if (typeof filename === 'function') {
  471. done = filename;
  472. name = null;
  473. opts = null
  474. } else if (typeof options === 'function') {
  475. done = options
  476. opts = null
  477. }
  478. // set Content-Disposition when file is sent
  479. var headers = {
  480. 'Content-Disposition': contentDisposition(name || path)
  481. };
  482. // merge user-provided headers
  483. if (opts && opts.headers) {
  484. var keys = Object.keys(opts.headers)
  485. for (var i = 0; i < keys.length; i++) {
  486. var key = keys[i]
  487. if (key.toLowerCase() !== 'content-disposition') {
  488. headers[key] = opts.headers[key]
  489. }
  490. }
  491. }
  492. // merge user-provided options
  493. opts = Object.create(opts)
  494. opts.headers = headers
  495. // Resolve the full path for sendFile
  496. var fullPath = resolve(path);
  497. // send file
  498. return this.sendFile(fullPath, opts, done)
  499. };
  500. /**
  501. * Set _Content-Type_ response header with `type` through `mime.lookup()`
  502. * when it does not contain "/", or set the Content-Type to `type` otherwise.
  503. *
  504. * Examples:
  505. *
  506. * res.type('.html');
  507. * res.type('html');
  508. * res.type('json');
  509. * res.type('application/json');
  510. * res.type('png');
  511. *
  512. * @param {String} type
  513. * @return {ServerResponse} for chaining
  514. * @public
  515. */
  516. res.contentType =
  517. res.type = function contentType(type) {
  518. var ct = type.indexOf('/') === -1
  519. ? mime.lookup(type)
  520. : type;
  521. return this.set('Content-Type', ct);
  522. };
  523. /**
  524. * Respond to the Acceptable formats using an `obj`
  525. * of mime-type callbacks.
  526. *
  527. * This method uses `req.accepted`, an array of
  528. * acceptable types ordered by their quality values.
  529. * When "Accept" is not present the _first_ callback
  530. * is invoked, otherwise the first match is used. When
  531. * no match is performed the server responds with
  532. * 406 "Not Acceptable".
  533. *
  534. * Content-Type is set for you, however if you choose
  535. * you may alter this within the callback using `res.type()`
  536. * or `res.set('Content-Type', ...)`.
  537. *
  538. * res.format({
  539. * 'text/plain': function(){
  540. * res.send('hey');
  541. * },
  542. *
  543. * 'text/html': function(){
  544. * res.send('<p>hey</p>');
  545. * },
  546. *
  547. * 'appliation/json': function(){
  548. * res.send({ message: 'hey' });
  549. * }
  550. * });
  551. *
  552. * In addition to canonicalized MIME types you may
  553. * also use extnames mapped to these types:
  554. *
  555. * res.format({
  556. * text: function(){
  557. * res.send('hey');
  558. * },
  559. *
  560. * html: function(){
  561. * res.send('<p>hey</p>');
  562. * },
  563. *
  564. * json: function(){
  565. * res.send({ message: 'hey' });
  566. * }
  567. * });
  568. *
  569. * By default Express passes an `Error`
  570. * with a `.status` of 406 to `next(err)`
  571. * if a match is not made. If you provide
  572. * a `.default` callback it will be invoked
  573. * instead.
  574. *
  575. * @param {Object} obj
  576. * @return {ServerResponse} for chaining
  577. * @public
  578. */
  579. res.format = function(obj){
  580. var req = this.req;
  581. var next = req.next;
  582. var fn = obj.default;
  583. if (fn) delete obj.default;
  584. var keys = Object.keys(obj);
  585. var key = keys.length > 0
  586. ? req.accepts(keys)
  587. : false;
  588. this.vary("Accept");
  589. if (key) {
  590. this.set('Content-Type', normalizeType(key).value);
  591. obj[key](req, this, next);
  592. } else if (fn) {
  593. fn();
  594. } else {
  595. var err = new Error('Not Acceptable');
  596. err.status = err.statusCode = 406;
  597. err.types = normalizeTypes(keys).map(function(o){ return o.value });
  598. next(err);
  599. }
  600. return this;
  601. };
  602. /**
  603. * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
  604. *
  605. * @param {String} filename
  606. * @return {ServerResponse}
  607. * @public
  608. */
  609. res.attachment = function attachment(filename) {
  610. if (filename) {
  611. this.type(extname(filename));
  612. }
  613. this.set('Content-Disposition', contentDisposition(filename));
  614. return this;
  615. };
  616. /**
  617. * Append additional header `field` with value `val`.
  618. *
  619. * Example:
  620. *
  621. * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
  622. * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
  623. * res.append('Warning', '199 Miscellaneous warning');
  624. *
  625. * @param {String} field
  626. * @param {String|Array} val
  627. * @return {ServerResponse} for chaining
  628. * @public
  629. */
  630. res.append = function append(field, val) {
  631. var prev = this.get(field);
  632. var value = val;
  633. if (prev) {
  634. // concat the new and prev vals
  635. value = Array.isArray(prev) ? prev.concat(val)
  636. : Array.isArray(val) ? [prev].concat(val)
  637. : [prev, val];
  638. }
  639. return this.set(field, value);
  640. };
  641. /**
  642. * Set header `field` to `val`, or pass
  643. * an object of header fields.
  644. *
  645. * Examples:
  646. *
  647. * res.set('Foo', ['bar', 'baz']);
  648. * res.set('Accept', 'application/json');
  649. * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
  650. *
  651. * Aliased as `res.header()`.
  652. *
  653. * @param {String|Object} field
  654. * @param {String|Array} val
  655. * @return {ServerResponse} for chaining
  656. * @public
  657. */
  658. res.set =
  659. res.header = function header(field, val) {
  660. if (arguments.length === 2) {
  661. var value = Array.isArray(val)
  662. ? val.map(String)
  663. : String(val);
  664. // add charset to content-type
  665. if (field.toLowerCase() === 'content-type') {
  666. if (Array.isArray(value)) {
  667. throw new TypeError('Content-Type cannot be set to an Array');
  668. }
  669. if (!charsetRegExp.test(value)) {
  670. var charset = mime.charsets.lookup(value.split(';')[0]);
  671. if (charset) value += '; charset=' + charset.toLowerCase();
  672. }
  673. }
  674. this.setHeader(field, value);
  675. } else {
  676. for (var key in field) {
  677. this.set(key, field[key]);
  678. }
  679. }
  680. return this;
  681. };
  682. /**
  683. * Get value for header `field`.
  684. *
  685. * @param {String} field
  686. * @return {String}
  687. * @public
  688. */
  689. res.get = function(field){
  690. return this.getHeader(field);
  691. };
  692. /**
  693. * Clear cookie `name`.
  694. *
  695. * @param {String} name
  696. * @param {Object} [options]
  697. * @return {ServerResponse} for chaining
  698. * @public
  699. */
  700. res.clearCookie = function clearCookie(name, options) {
  701. var opts = merge({ expires: new Date(1), path: '/' }, options);
  702. return this.cookie(name, '', opts);
  703. };
  704. /**
  705. * Set cookie `name` to `value`, with the given `options`.
  706. *
  707. * Options:
  708. *
  709. * - `maxAge` max-age in milliseconds, converted to `expires`
  710. * - `signed` sign the cookie
  711. * - `path` defaults to "/"
  712. *
  713. * Examples:
  714. *
  715. * // "Remember Me" for 15 minutes
  716. * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
  717. *
  718. * // same as above
  719. * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
  720. *
  721. * @param {String} name
  722. * @param {String|Object} value
  723. * @param {Object} [options]
  724. * @return {ServerResponse} for chaining
  725. * @public
  726. */
  727. res.cookie = function (name, value, options) {
  728. var opts = merge({}, options);
  729. var secret = this.req.secret;
  730. var signed = opts.signed;
  731. if (signed && !secret) {
  732. throw new Error('cookieParser("secret") required for signed cookies');
  733. }
  734. var val = typeof value === 'object'
  735. ? 'j:' + JSON.stringify(value)
  736. : String(value);
  737. if (signed) {
  738. val = 's:' + sign(val, secret);
  739. }
  740. if ('maxAge' in opts) {
  741. opts.expires = new Date(Date.now() + opts.maxAge);
  742. opts.maxAge /= 1000;
  743. }
  744. if (opts.path == null) {
  745. opts.path = '/';
  746. }
  747. this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
  748. return this;
  749. };
  750. /**
  751. * Set the location header to `url`.
  752. *
  753. * The given `url` can also be "back", which redirects
  754. * to the _Referrer_ or _Referer_ headers or "/".
  755. *
  756. * Examples:
  757. *
  758. * res.location('/foo/bar').;
  759. * res.location('http://example.com');
  760. * res.location('../login');
  761. *
  762. * @param {String} url
  763. * @return {ServerResponse} for chaining
  764. * @public
  765. */
  766. res.location = function location(url) {
  767. var loc = url;
  768. // "back" is an alias for the referrer
  769. if (url === 'back') {
  770. loc = this.req.get('Referrer') || '/';
  771. }
  772. // set location
  773. return this.set('Location', encodeUrl(loc));
  774. };
  775. /**
  776. * Redirect to the given `url` with optional response `status`
  777. * defaulting to 302.
  778. *
  779. * The resulting `url` is determined by `res.location()`, so
  780. * it will play nicely with mounted apps, relative paths,
  781. * `"back"` etc.
  782. *
  783. * Examples:
  784. *
  785. * res.redirect('/foo/bar');
  786. * res.redirect('http://example.com');
  787. * res.redirect(301, 'http://example.com');
  788. * res.redirect('../login'); // /blog/post/1 -> /blog/login
  789. *
  790. * @public
  791. */
  792. res.redirect = function redirect(url) {
  793. var address = url;
  794. var body;
  795. var status = 302;
  796. // allow status / url
  797. if (arguments.length === 2) {
  798. if (typeof arguments[0] === 'number') {
  799. status = arguments[0];
  800. address = arguments[1];
  801. } else {
  802. deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
  803. status = arguments[1];
  804. }
  805. }
  806. // Set location header
  807. address = this.location(address).get('Location');
  808. // Support text/{plain,html} by default
  809. this.format({
  810. text: function(){
  811. body = statuses[status] + '. Redirecting to ' + address
  812. },
  813. html: function(){
  814. var u = escapeHtml(address);
  815. body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
  816. },
  817. default: function(){
  818. body = '';
  819. }
  820. });
  821. // Respond
  822. this.statusCode = status;
  823. this.set('Content-Length', Buffer.byteLength(body));
  824. if (this.req.method === 'HEAD') {
  825. this.end();
  826. } else {
  827. this.end(body);
  828. }
  829. };
  830. /**
  831. * Add `field` to Vary. If already present in the Vary set, then
  832. * this call is simply ignored.
  833. *
  834. * @param {Array|String} field
  835. * @return {ServerResponse} for chaining
  836. * @public
  837. */
  838. res.vary = function(field){
  839. // checks for back-compat
  840. if (!field || (Array.isArray(field) && !field.length)) {
  841. deprecate('res.vary(): Provide a field name');
  842. return this;
  843. }
  844. vary(this, field);
  845. return this;
  846. };
  847. /**
  848. * Render `view` with the given `options` and optional callback `fn`.
  849. * When a callback function is given a response will _not_ be made
  850. * automatically, otherwise a response of _200_ and _text/html_ is given.
  851. *
  852. * Options:
  853. *
  854. * - `cache` boolean hinting to the engine it should cache
  855. * - `filename` filename of the view being rendered
  856. *
  857. * @public
  858. */
  859. res.render = function render(view, options, callback) {
  860. var app = this.req.app;
  861. var done = callback;
  862. var opts = options || {};
  863. var req = this.req;
  864. var self = this;
  865. // support callback function as second arg
  866. if (typeof options === 'function') {
  867. done = options;
  868. opts = {};
  869. }
  870. // merge res.locals
  871. opts._locals = self.locals;
  872. // default callback to respond
  873. done = done || function (err, str) {
  874. if (err) return req.next(err);
  875. self.send(str);
  876. };
  877. // render
  878. app.render(view, opts, done);
  879. };
  880. // pipe the send file stream
  881. function sendfile(res, file, options, callback) {
  882. var done = false;
  883. var streaming;
  884. // request aborted
  885. function onaborted() {
  886. if (done) return;
  887. done = true;
  888. var err = new Error('Request aborted');
  889. err.code = 'ECONNABORTED';
  890. callback(err);
  891. }
  892. // directory
  893. function ondirectory() {
  894. if (done) return;
  895. done = true;
  896. var err = new Error('EISDIR, read');
  897. err.code = 'EISDIR';
  898. callback(err);
  899. }
  900. // errors
  901. function onerror(err) {
  902. if (done) return;
  903. done = true;
  904. callback(err);
  905. }
  906. // ended
  907. function onend() {
  908. if (done) return;
  909. done = true;
  910. callback();
  911. }
  912. // file
  913. function onfile() {
  914. streaming = false;
  915. }
  916. // finished
  917. function onfinish(err) {
  918. if (err && err.code === 'ECONNRESET') return onaborted();
  919. if (err) return onerror(err);
  920. if (done) return;
  921. setImmediate(function () {
  922. if (streaming !== false && !done) {
  923. onaborted();
  924. return;
  925. }
  926. if (done) return;
  927. done = true;
  928. callback();
  929. });
  930. }
  931. // streaming
  932. function onstream() {
  933. streaming = true;
  934. }
  935. file.on('directory', ondirectory);
  936. file.on('end', onend);
  937. file.on('error', onerror);
  938. file.on('file', onfile);
  939. file.on('stream', onstream);
  940. onFinished(res, onfinish);
  941. if (options.headers) {
  942. // set headers on successful transfer
  943. file.on('headers', function headers(res) {
  944. var obj = options.headers;
  945. var keys = Object.keys(obj);
  946. for (var i = 0; i < keys.length; i++) {
  947. var k = keys[i];
  948. res.setHeader(k, obj[k]);
  949. }
  950. });
  951. }
  952. // pipe
  953. file.pipe(res);
  954. }
  955. /**
  956. * Stringify JSON, like JSON.stringify, but v8 optimized, with the
  957. * ability to escape characters that can trigger HTML sniffing.
  958. *
  959. * @param {*} value
  960. * @param {function} replaces
  961. * @param {number} spaces
  962. * @param {boolean} escape
  963. * @returns {string}
  964. * @private
  965. */
  966. function stringify (value, replacer, spaces, escape) {
  967. // v8 checks arguments.length for optimizing simple call
  968. // https://bugs.chromium.org/p/v8/issues/detail?id=4730
  969. var json = replacer || spaces
  970. ? JSON.stringify(value, replacer, spaces)
  971. : JSON.stringify(value);
  972. if (escape) {
  973. json = json.replace(/[<>&]/g, function (c) {
  974. switch (c.charCodeAt(0)) {
  975. case 0x3c:
  976. return '\\u003c'
  977. case 0x3e:
  978. return '\\u003e'
  979. case 0x26:
  980. return '\\u0026'
  981. /* istanbul ignore next: unreachable default */
  982. default:
  983. return c
  984. }
  985. })
  986. }
  987. return json
  988. }