3 * Copyright(c) 2009-2013 TJ Holowaychuk
4 * Copyright(c) 2014-2015 Douglas Christopher Wilson
11 * Module dependencies.
15 var Buffer = require('safe-buffer').Buffer
16 var contentDisposition = require('content-disposition');
17 var deprecate = require('depd')('express');
18 var encodeUrl = require('encodeurl');
19 var escapeHtml = require('escape-html');
20 var http = require('http');
21 var isAbsolute = require('./utils').isAbsolute;
22 var onFinished = require('on-finished');
23 var path = require('path');
24 var statuses = require('statuses')
25 var merge = require('utils-merge');
26 var sign = require('cookie-signature').sign;
27 var normalizeType = require('./utils').normalizeType;
28 var normalizeTypes = require('./utils').normalizeTypes;
29 var setCharset = require('./utils').setCharset;
30 var cookie = require('cookie');
31 var send = require('send');
32 var extname = path.extname;
34 var resolve = path.resolve;
35 var vary = require('vary');
42 var res = Object.create(http.ServerResponse.prototype)
56 var charsetRegExp = /;\s*charset\s*=/;
61 * @param {Number} code
62 * @return {ServerResponse}
66 res.status = function status(code) {
67 this.statusCode = code;
72 * Set Link header field with the given `links`.
77 * next: 'http://api.example.com/users?page=2',
78 * last: 'http://api.example.com/users?page=5'
81 * @param {Object} links
82 * @return {ServerResponse}
86 res.links = function(links){
87 var link = this.get('Link') || '';
88 if (link) link += ', ';
89 return this.set('Link', link + Object.keys(links).map(function(rel){
90 return '<' + links[rel] + '>; rel="' + rel + '"';
99 * res.send(Buffer.from('wahoo'));
100 * res.send({ some: 'json' });
101 * res.send('<p>some html</p>');
103 * @param {string|number|boolean|object|Buffer} body
107 res.send = function send(body) {
116 // allow status / body
117 if (arguments.length === 2) {
118 // res.send(body, status) backwards compat
119 if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
120 deprecate('res.send(body, status): Use res.status(status).send(body) instead');
121 this.statusCode = arguments[1];
123 deprecate('res.send(status, body): Use res.status(status).send(body) instead');
124 this.statusCode = arguments[0];
125 chunk = arguments[1];
129 // disambiguate res.send(status) and res.send(status, num)
130 if (typeof chunk === 'number' && arguments.length === 1) {
131 // res.send(status) will set status message as text string
132 if (!this.get('Content-Type')) {
136 deprecate('res.send(status): Use res.sendStatus(status) instead');
137 this.statusCode = chunk;
138 chunk = statuses[chunk]
141 switch (typeof chunk) {
142 // string defaulting to html
144 if (!this.get('Content-Type')) {
151 if (chunk === null) {
153 } else if (Buffer.isBuffer(chunk)) {
154 if (!this.get('Content-Type')) {
158 return this.json(chunk);
163 // write strings in utf-8
164 if (typeof chunk === 'string') {
166 type = this.get('Content-Type');
168 // reflect this in content-type
169 if (typeof type === 'string') {
170 this.set('Content-Type', setCharset(type, 'utf-8'));
174 // determine if ETag should be generated
175 var etagFn = app.get('etag fn')
176 var generateETag = !this.get('ETag') && typeof etagFn === 'function'
178 // populate Content-Length
180 if (chunk !== undefined) {
181 if (Buffer.isBuffer(chunk)) {
182 // get length of Buffer
184 } else if (!generateETag && chunk.length < 1000) {
185 // just calculate length when no ETag + small chunk
186 len = Buffer.byteLength(chunk, encoding)
188 // convert chunk to Buffer and calculate
189 chunk = Buffer.from(chunk, encoding)
190 encoding = undefined;
194 this.set('Content-Length', len);
199 if (generateETag && len !== undefined) {
200 if ((etag = etagFn(chunk, encoding))) {
201 this.set('ETag', etag);
206 if (req.fresh) this.statusCode = 304;
208 // strip irrelevant headers
209 if (204 === this.statusCode || 304 === this.statusCode) {
210 this.removeHeader('Content-Type');
211 this.removeHeader('Content-Length');
212 this.removeHeader('Transfer-Encoding');
216 if (req.method === 'HEAD') {
217 // skip body for HEAD
221 this.end(chunk, encoding);
228 * Send JSON response.
233 * res.json({ user: 'tj' });
235 * @param {string|number|boolean|object} obj
239 res.json = function json(obj) {
242 // allow status / body
243 if (arguments.length === 2) {
244 // res.json(body, status) backwards compat
245 if (typeof arguments[1] === 'number') {
246 deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
247 this.statusCode = arguments[1];
249 deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
250 this.statusCode = arguments[0];
257 var escape = app.get('json escape')
258 var replacer = app.get('json replacer');
259 var spaces = app.get('json spaces');
260 var body = stringify(val, replacer, spaces, escape)
263 if (!this.get('Content-Type')) {
264 this.set('Content-Type', 'application/json');
267 return this.send(body);
271 * Send JSON response with JSONP callback support.
276 * res.jsonp({ user: 'tj' });
278 * @param {string|number|boolean|object} obj
282 res.jsonp = function jsonp(obj) {
285 // allow status / body
286 if (arguments.length === 2) {
287 // res.json(body, status) backwards compat
288 if (typeof arguments[1] === 'number') {
289 deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');
290 this.statusCode = arguments[1];
292 deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
293 this.statusCode = arguments[0];
300 var escape = app.get('json escape')
301 var replacer = app.get('json replacer');
302 var spaces = app.get('json spaces');
303 var body = stringify(val, replacer, spaces, escape)
304 var callback = this.req.query[app.get('jsonp callback name')];
307 if (!this.get('Content-Type')) {
308 this.set('X-Content-Type-Options', 'nosniff');
309 this.set('Content-Type', 'application/json');
313 if (Array.isArray(callback)) {
314 callback = callback[0];
318 if (typeof callback === 'string' && callback.length !== 0) {
319 this.set('X-Content-Type-Options', 'nosniff');
320 this.set('Content-Type', 'text/javascript');
322 // restrict callback charset
323 callback = callback.replace(/[^\[\]\w$.]/g, '');
325 // replace chars not allowed in JavaScript that are in JSON
327 .replace(/\u2028/g, '\\u2028')
328 .replace(/\u2029/g, '\\u2029');
330 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
331 // the typeof check is just to reduce client error noise
332 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
335 return this.send(body);
339 * Send given HTTP status code.
341 * Sets the response status to `statusCode` and the body of the
342 * response to the standard description from node's http.STATUS_CODES
343 * or the statusCode number if no description.
347 * res.sendStatus(200);
349 * @param {number} statusCode
353 res.sendStatus = function sendStatus(statusCode) {
354 var body = statuses[statusCode] || String(statusCode)
356 this.statusCode = statusCode;
359 return this.send(body);
363 * Transfer the file at the given `path`.
365 * Automatically sets the _Content-Type_ response header field.
366 * The callback `callback(err)` is invoked when the transfer is complete
367 * or when an error occurs. Be sure to check `res.sentHeader`
368 * if you wish to attempt responding, as the header and some data
369 * may have already been transferred.
373 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
374 * - `root` root directory for relative filenames
375 * - `headers` object of headers to serve with file
376 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
378 * Other options are passed along to `send`.
382 * The following example illustrates how `res.sendFile()` may
383 * be used as an alternative for the `static()` middleware for
384 * dynamic situations. The code backing `res.sendFile()` is actually
385 * the same code, so HTTP cache support etc is identical.
387 * app.get('/user/:uid/photos/:file', function(req, res){
388 * var uid = req.params.uid
389 * , file = req.params.file;
391 * req.user.mayViewFilesFrom(uid, function(yes){
393 * res.sendFile('/uploads/' + uid + '/' + file);
395 * res.send(403, 'Sorry! you cant see that.');
403 res.sendFile = function sendFile(path, options, callback) {
408 var opts = options || {};
411 throw new TypeError('path argument is required to res.sendFile');
414 if (typeof path !== 'string') {
415 throw new TypeError('path must be a string to res.sendFile')
418 // support function as second arg
419 if (typeof options === 'function') {
424 if (!opts.root && !isAbsolute(path)) {
425 throw new TypeError('path must be absolute or specify root to res.sendFile');
428 // create file stream
429 var pathname = encodeURI(path);
430 var file = send(req, pathname, opts);
433 sendfile(res, file, opts, function (err) {
434 if (done) return done(err);
435 if (err && err.code === 'EISDIR') return next();
437 // next() all but write errors
438 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
445 * Transfer the file at the given `path`.
447 * Automatically sets the _Content-Type_ response header field.
448 * The callback `callback(err)` is invoked when the transfer is complete
449 * or when an error occurs. Be sure to check `res.sentHeader`
450 * if you wish to attempt responding, as the header and some data
451 * may have already been transferred.
455 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
456 * - `root` root directory for relative filenames
457 * - `headers` object of headers to serve with file
458 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
460 * Other options are passed along to `send`.
464 * The following example illustrates how `res.sendfile()` may
465 * be used as an alternative for the `static()` middleware for
466 * dynamic situations. The code backing `res.sendfile()` is actually
467 * the same code, so HTTP cache support etc is identical.
469 * app.get('/user/:uid/photos/:file', function(req, res){
470 * var uid = req.params.uid
471 * , file = req.params.file;
473 * req.user.mayViewFilesFrom(uid, function(yes){
475 * res.sendfile('/uploads/' + uid + '/' + file);
477 * res.send(403, 'Sorry! you cant see that.');
485 res.sendfile = function (path, options, callback) {
490 var opts = options || {};
492 // support function as second arg
493 if (typeof options === 'function') {
498 // create file stream
499 var file = send(req, path, opts);
502 sendfile(res, file, opts, function (err) {
503 if (done) return done(err);
504 if (err && err.code === 'EISDIR') return next();
506 // next() all but write errors
507 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
513 res.sendfile = deprecate.function(res.sendfile,
514 'res.sendfile: Use res.sendFile instead');
517 * Transfer the file at the given `path` as an attachment.
519 * Optionally providing an alternate attachment `filename`,
520 * and optional callback `callback(err)`. The callback is invoked
521 * when the data transfer is complete, or when an error has
522 * ocurred. Be sure to check `res.headersSent` if you plan to respond.
524 * Optionally providing an `options` object to use with `res.sendFile()`.
525 * This function will set the `Content-Disposition` header, overriding
526 * any `Content-Disposition` header passed as header options in order
527 * to set the attachment and filename.
529 * This method uses `res.sendFile()`.
534 res.download = function download (path, filename, options, callback) {
537 var opts = options || null
539 // support function as second or third arg
540 if (typeof filename === 'function') {
544 } else if (typeof options === 'function') {
549 // set Content-Disposition when file is sent
551 'Content-Disposition': contentDisposition(name || path)
554 // merge user-provided headers
555 if (opts && opts.headers) {
556 var keys = Object.keys(opts.headers)
557 for (var i = 0; i < keys.length; i++) {
559 if (key.toLowerCase() !== 'content-disposition') {
560 headers[key] = opts.headers[key]
565 // merge user-provided options
566 opts = Object.create(opts)
567 opts.headers = headers
569 // Resolve the full path for sendFile
570 var fullPath = resolve(path);
573 return this.sendFile(fullPath, opts, done)
577 * Set _Content-Type_ response header with `type` through `mime.lookup()`
578 * when it does not contain "/", or set the Content-Type to `type` otherwise.
585 * res.type('application/json');
588 * @param {String} type
589 * @return {ServerResponse} for chaining
594 res.type = function contentType(type) {
595 var ct = type.indexOf('/') === -1
599 return this.set('Content-Type', ct);
603 * Respond to the Acceptable formats using an `obj`
604 * of mime-type callbacks.
606 * This method uses `req.accepted`, an array of
607 * acceptable types ordered by their quality values.
608 * When "Accept" is not present the _first_ callback
609 * is invoked, otherwise the first match is used. When
610 * no match is performed the server responds with
611 * 406 "Not Acceptable".
613 * Content-Type is set for you, however if you choose
614 * you may alter this within the callback using `res.type()`
615 * or `res.set('Content-Type', ...)`.
618 * 'text/plain': function(){
622 * 'text/html': function(){
623 * res.send('<p>hey</p>');
626 * 'appliation/json': function(){
627 * res.send({ message: 'hey' });
631 * In addition to canonicalized MIME types you may
632 * also use extnames mapped to these types:
640 * res.send('<p>hey</p>');
644 * res.send({ message: 'hey' });
648 * By default Express passes an `Error`
649 * with a `.status` of 406 to `next(err)`
650 * if a match is not made. If you provide
651 * a `.default` callback it will be invoked
654 * @param {Object} obj
655 * @return {ServerResponse} for chaining
659 res.format = function(obj){
663 var fn = obj.default;
664 if (fn) delete obj.default;
665 var keys = Object.keys(obj);
667 var key = keys.length > 0
674 this.set('Content-Type', normalizeType(key).value);
675 obj[key](req, this, next);
679 var err = new Error('Not Acceptable');
680 err.status = err.statusCode = 406;
681 err.types = normalizeTypes(keys).map(function(o){ return o.value });
689 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
691 * @param {String} filename
692 * @return {ServerResponse}
696 res.attachment = function attachment(filename) {
698 this.type(extname(filename));
701 this.set('Content-Disposition', contentDisposition(filename));
707 * Append additional header `field` with value `val`.
711 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
712 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
713 * res.append('Warning', '199 Miscellaneous warning');
715 * @param {String} field
716 * @param {String|Array} val
717 * @return {ServerResponse} for chaining
721 res.append = function append(field, val) {
722 var prev = this.get(field);
726 // concat the new and prev vals
727 value = Array.isArray(prev) ? prev.concat(val)
728 : Array.isArray(val) ? [prev].concat(val)
732 return this.set(field, value);
736 * Set header `field` to `val`, or pass
737 * an object of header fields.
741 * res.set('Foo', ['bar', 'baz']);
742 * res.set('Accept', 'application/json');
743 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
745 * Aliased as `res.header()`.
747 * @param {String|Object} field
748 * @param {String|Array} val
749 * @return {ServerResponse} for chaining
754 res.header = function header(field, val) {
755 if (arguments.length === 2) {
756 var value = Array.isArray(val)
760 // add charset to content-type
761 if (field.toLowerCase() === 'content-type') {
762 if (Array.isArray(value)) {
763 throw new TypeError('Content-Type cannot be set to an Array');
765 if (!charsetRegExp.test(value)) {
766 var charset = mime.charsets.lookup(value.split(';')[0]);
767 if (charset) value += '; charset=' + charset.toLowerCase();
771 this.setHeader(field, value);
773 for (var key in field) {
774 this.set(key, field[key]);
781 * Get value for header `field`.
783 * @param {String} field
788 res.get = function(field){
789 return this.getHeader(field);
793 * Clear cookie `name`.
795 * @param {String} name
796 * @param {Object} [options]
797 * @return {ServerResponse} for chaining
801 res.clearCookie = function clearCookie(name, options) {
802 var opts = merge({ expires: new Date(1), path: '/' }, options);
804 return this.cookie(name, '', opts);
808 * Set cookie `name` to `value`, with the given `options`.
812 * - `maxAge` max-age in milliseconds, converted to `expires`
813 * - `signed` sign the cookie
814 * - `path` defaults to "/"
818 * // "Remember Me" for 15 minutes
819 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
822 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
824 * @param {String} name
825 * @param {String|Object} value
826 * @param {Object} [options]
827 * @return {ServerResponse} for chaining
831 res.cookie = function (name, value, options) {
832 var opts = merge({}, options);
833 var secret = this.req.secret;
834 var signed = opts.signed;
836 if (signed && !secret) {
837 throw new Error('cookieParser("secret") required for signed cookies');
840 var val = typeof value === 'object'
841 ? 'j:' + JSON.stringify(value)
845 val = 's:' + sign(val, secret);
848 if ('maxAge' in opts) {
849 opts.expires = new Date(Date.now() + opts.maxAge);
853 if (opts.path == null) {
857 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
863 * Set the location header to `url`.
865 * The given `url` can also be "back", which redirects
866 * to the _Referrer_ or _Referer_ headers or "/".
870 * res.location('/foo/bar').;
871 * res.location('http://example.com');
872 * res.location('../login');
874 * @param {String} url
875 * @return {ServerResponse} for chaining
879 res.location = function location(url) {
882 // "back" is an alias for the referrer
883 if (url === 'back') {
884 loc = this.req.get('Referrer') || '/';
888 return this.set('Location', encodeUrl(loc));
892 * Redirect to the given `url` with optional response `status`
895 * The resulting `url` is determined by `res.location()`, so
896 * it will play nicely with mounted apps, relative paths,
901 * res.redirect('/foo/bar');
902 * res.redirect('http://example.com');
903 * res.redirect(301, 'http://example.com');
904 * res.redirect('../login'); // /blog/post/1 -> /blog/login
909 res.redirect = function redirect(url) {
914 // allow status / url
915 if (arguments.length === 2) {
916 if (typeof arguments[0] === 'number') {
917 status = arguments[0];
918 address = arguments[1];
920 deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
921 status = arguments[1];
925 // Set location header
926 address = this.location(address).get('Location');
928 // Support text/{plain,html} by default
931 body = statuses[status] + '. Redirecting to ' + address
935 var u = escapeHtml(address);
936 body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
945 this.statusCode = status;
946 this.set('Content-Length', Buffer.byteLength(body));
948 if (this.req.method === 'HEAD') {
956 * Add `field` to Vary. If already present in the Vary set, then
957 * this call is simply ignored.
959 * @param {Array|String} field
960 * @return {ServerResponse} for chaining
964 res.vary = function(field){
965 // checks for back-compat
966 if (!field || (Array.isArray(field) && !field.length)) {
967 deprecate('res.vary(): Provide a field name');
977 * Render `view` with the given `options` and optional callback `fn`.
978 * When a callback function is given a response will _not_ be made
979 * automatically, otherwise a response of _200_ and _text/html_ is given.
983 * - `cache` boolean hinting to the engine it should cache
984 * - `filename` filename of the view being rendered
989 res.render = function render(view, options, callback) {
990 var app = this.req.app;
992 var opts = options || {};
996 // support callback function as second arg
997 if (typeof options === 'function') {
1003 opts._locals = self.locals;
1005 // default callback to respond
1006 done = done || function (err, str) {
1007 if (err) return req.next(err);
1012 app.render(view, opts, done);
1015 // pipe the send file stream
1016 function sendfile(res, file, options, callback) {
1021 function onaborted() {
1025 var err = new Error('Request aborted');
1026 err.code = 'ECONNABORTED';
1031 function ondirectory() {
1035 var err = new Error('EISDIR, read');
1036 err.code = 'EISDIR';
1041 function onerror(err) {
1060 function onfinish(err) {
1061 if (err && err.code === 'ECONNRESET') return onaborted();
1062 if (err) return onerror(err);
1065 setImmediate(function () {
1066 if (streaming !== false && !done) {
1078 function onstream() {
1082 file.on('directory', ondirectory);
1083 file.on('end', onend);
1084 file.on('error', onerror);
1085 file.on('file', onfile);
1086 file.on('stream', onstream);
1087 onFinished(res, onfinish);
1089 if (options.headers) {
1090 // set headers on successful transfer
1091 file.on('headers', function headers(res) {
1092 var obj = options.headers;
1093 var keys = Object.keys(obj);
1095 for (var i = 0; i < keys.length; i++) {
1097 res.setHeader(k, obj[k]);
1107 * Stringify JSON, like JSON.stringify, but v8 optimized, with the
1108 * ability to escape characters that can trigger HTML sniffing.
1111 * @param {function} replaces
1112 * @param {number} spaces
1113 * @param {boolean} escape
1118 function stringify (value, replacer, spaces, escape) {
1119 // v8 checks arguments.length for optimizing simple call
1120 // https://bugs.chromium.org/p/v8/issues/detail?id=4730
1121 var json = replacer || spaces
1122 ? JSON.stringify(value, replacer, spaces)
1123 : JSON.stringify(value);
1126 json = json.replace(/[<>&]/g, function (c) {
1127 switch (c.charCodeAt(0)) {
1134 /* istanbul ignore next: unreachable default */