Node-Red configuration
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

response.js 28KB

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