response.js
This file
Path
lib/response.js
455 lines · 10.7 KiB · JavaScript
Last changed by
Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994
History of this fileTake it
The walk stopped after 200 commits: lines older than 058777b point at it.
connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 1–19why, one step back12/*!3 * Express - response4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var fs = require('fs')13 , http = require('http')14 , path = require('path')15 , connect = require('connect')16 , utils = connect.utils17 , parseRange = require('./utils').parseRange18 , res = http.ServerResponse.prototype19 , send = connect.static.sendmisc refactoringTj Holowaychukbefore adoption70e6baf
lines 20–22why, one step back20 , mime = require('mime')21 , basename = path.basename22 , join = path.join;connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 23–62why, one step back2324/**25 * Send a response with the given `body` and optional `headers` and `status` code.26 *27 * Examples:28 *29 * res.send(new Buffer('wahoo'));30 * res.send({ some: 'json' });31 * res.send('<p>some html</p>');32 * res.send('Sorry, cant find that', 404);33 * res.send('text', { 'Content-Type': 'text/plain' }, 201);34 * res.send(404);35 *36 * @param {String|Object|Number|Buffer} body or status37 * @param {Object|Number} headers or status38 * @param {Number} status39 * @return {ServerResponse}40 * @api public41 */4243res.send = function(body, headers, status){44 // allow status as second arg45 if ('number' == typeof headers) {46 status = headers,47 headers = null;48 }4950 // default status51 status = status || this.statusCode;5253 // determine content type54 switch (typeof body) {55 case 'number':56 if (!this.header('Content-Type')) {57 this.contentType('.txt');58 }59 body = http.STATUS_CODES[status = body];60 break;61 case 'string':62 if (!this.header('Content-Type')) {JSON and JSONP default to UTF-8 in the same way as HTML. Closes #632.Daniel Shawbefore adoption3afbcd0
line 63why, one step back63 this.charset = this.charset || 'utf-8';connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 64–73why, one step back64 this.contentType('.html');65 }66 break;67 case 'boolean':68 case 'object':69 if (Buffer.isBuffer(body)) {70 if (!this.header('Content-Type')) {71 this.contentType('.bin');72 }73 } else {res.send() using res.json()Tj Holowaychukbefore adoption2aaf0de
line 74why, one step back74 return this.json(body, headers, status);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 75–95why, one step back75 }76 break;77 }7879 // populate Content-Length80 if (!this.header('Content-Length')) {81 this.header('Content-Length', Buffer.isBuffer(body)82 ? body.length83 : Buffer.byteLength(body));84 }8586 // merge headers passed87 if (headers) {88 var fields = Object.keys(headers);89 for (var i = 0, len = fields.length; i < len; ++i) {90 var field = fields[i];91 this.header(field, headers[field]);92 }93 }9495 // strip irrelevant headersFixed; ignore body on 304. Closes #701Tj Holowaychukbefore adoption9028cac
line 96why, one step back96 if (204 == status || 304 == status) {connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 97–103why, one step back97 this.removeHeader('Content-Type');98 this.removeHeader('Content-Length');99 }100101 // respond102 this.statusCode = status;103 this.end('HEAD' == this.req.method ? undefined : body);Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 104–124why, one step back104 return this;105};106107/**108 * Send JSON response with `obj`, optional `headers`, and optional `status`.109 *110 * Examples:111 *112 * res.json(null);113 * res.json({ user: 'tj' });114 * res.json('oh noes!', 500);115 * res.json('I dont have that', 404);116 *117 * @param {Mixed} obj118 * @param {Object|Number} headers or status119 * @param {Number} status120 * @return {ServerResponse}121 * @api public122 */123124res.json = function(obj, headers, status){Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 125–128why, one step back125 var body = JSON.stringify(obj)126 , callback = this.req.query.callback127 , jsonp = this.app.enabled('jsonp callback');128Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e
lines 129–130why, one step back129 this.charset = this.charset || 'utf-8';130 this.header('Content-Type', 'application/json');Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 131–133why, one step back131132 if (callback && jsonp) {133 this.header('Content-Type', 'text/javascript');Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea
line 134why, one step back134 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd
lines 135–137why, one step back135 }136137 return this.send(body, headers, status);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 138–139why, one step back138};139docs for res.status()Tj Holowaychukbefore adoption9477c9b
lines 140–147why, one step back140/**141 * Set status `code`.142 *143 * @param {Number} code144 * @return {ServerResponse}145 * @api public146 */147Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51
lines 148–152why, one step back148res.status = function(code){149 this.statusCode = code;150 return this;151};152connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 153–169why, one step back153/**154 * Transfer the file at the given `path`. Automatically sets 155 * the _Content-Type_ response header field. `next()` is called156 * when `path` is a directory, or when an error occurs.157 *158 * Options:159 *160 * - `maxAge` defaulting to 0161 * - `root` root directory for relative filenames162 *163 * @param {String} path164 * @param {Object|Function} options or fn165 * @param {Function} fn166 * @api public167 */168169res.sendfile = function(path, options, fn){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 170why, one step back170 var next = this.req.next;connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 171–178why, one step back171 options = options || {};172173 // support function as second arg174 if ('function' == typeof options) {175 fn = options;176 options = {};177 }178Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608
line 179why, one step back179 options.path = encodeURIComponent(path);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
line 180why, one step back180 options.callback = fn;Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 181why, one step back181 send(this.req, this, next, options);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 182–215why, one step back182};183184/**185 * Set _Content-Type_ response header passed through `mime.lookup()`.186 *187 * Examples:188 *189 * var filename = 'path/to/image.png';190 * res.contentType(filename);191 * // res.headers['Content-Type'] is now "image/png"192 *193 * res.contentType('.html');194 * res.contentType('html');195 * res.contentType('json');196 * res.contentType('png');197 *198 * @param {String} type199 * @return {String} the resolved mime type200 * @api public201 */202203res.contentType = function(type){204 return this.header('Content-Type', mime.lookup(type));205};206207/**208 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.209 *210 * @param {String} filename211 * @return {ServerResponse}212 * @api public213 */214215res.attachment = function(filename){auto set Content-Type in res.attachementAaron Heckmannbefore adoptione0bc571
line 216why, one step back216 if (filename) this.contentType(filename);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
line 217why, one step back217 this.header('Content-Disposition', filenamemisc refactoringTj Holowaychukbefore adoption70e6baf
line 218why, one step back218 ? 'attachment; filename="' + basename(filename) + '"'connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 219–224why, one step back219 : 'attachment');220 return this;221};222223/**224 * Transfer the file at the given `path`, with optional Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 225–226why, one step back225 * `filename` as an attachment and optional callback `fn(err)`,226 * and optional `fn2(err)` which is invoked when an error hastypoTj Holowaychukbefore adoption0cbb1f6
line 227why, one step back227 * occurred after header has been sent.connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 228–231why, one step back228 *229 * @param {String} path230 * @param {String|Function} filename or fn231 * @param {Function} fnAdded second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 232why, one step back232 * @param {Function} fn2connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 233–235why, one step back233 * @api public234 */235Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 236why, one step back236res.download = function(path, filename, fn, fn2){connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 237–240why, one step back237 var self = this;238239 // support callback as second arg240 if ('function' == typeof filename) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 241why, one step back241 fn2 = fn;connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 242–247why, one step back242 fn = filename;243 filename = null;244 }245246 // transfer the file247 this.attachment(filename || path).sendfile(path, function(err){Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
line 248why, one step back248 var sentHeader = self._header;connect >= 1.1.6Tj Holowaychukbefore adoption058777b
line 249why, one step back249 if (err) {Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 250–251why, one step back250 if (!sentHeader) self.removeHeader('Content-Disposition');251 if (sentHeader) {misc refactorTj Holowaychukbefore adoptionaa68581
line 252why, one step back252 fn2 && fn2(err);Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b
lines 253–259why, one step back253 } else if (fn) {254 fn(err);255 } else {256 self.req.next(err);257 }258 } else if (fn) {259 fn();connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 260–285why, one step back260 }261 });262};263264/**265 * Set or get response header `name` with optional `val`.266 *267 * @param {String} name268 * @param {String} val269 * @return {String}270 * @api public271 */272273res.header = function(name, val){274 if (val === undefined) {275 return this.getHeader(name);276 } else {277 this.setHeader(name, val);278 return val;279 }280};281282/**283 * Clear cookie `name`.284 *285 * @param {String} nameAdded options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
line 286why, one step back286 * @param {Object} optionsconnect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 287–289why, one step back287 * @api public288 */289Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d
lines 290–294why, one step back290res.clearCookie = function(name, options){291 var opts = { expires: new Date(1) };292 this.cookie(name, '', options293 ? utils.merge(options, opts)294 : opts);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 295–302why, one step back295};296297/**298 * Set cookie `name` to `val`, with the given `options`.299 *300 * Options:301 *302 * - `maxAge` max-age in milliseconds, converted to `expires`Changed; default cookie path to "home" setting. Closes #731Tj Holowaychukbefore adoption09c9452
line 303why, one step back303 * - `path` defaults to the "home" setting which is typically "/"connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 304–321why, one step back304 *305 * Examples:306 *307 * // "Remember Me" for 15 minutes308 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });309 *310 * // save as above311 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })312 *313 * @param {String} name314 * @param {String} val315 * @param {Options} options316 * @api public317 */318319res.cookie = function(name, val, options){320 options = options || {};321 if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge);when cookie path === null dont default itTj Holowaychukbefore adoptionee4471b
line 322why, one step back322 if (undefined === options.path) options.path = this.app.set('home');connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 323–398why, one step back323 var cookie = utils.serializeCookie(name, val, options);324 this.header('Set-Cookie', cookie);325};326327/**328 * Redirect to the given `url` with optional response `status`329 * defauling to 302.330 *331 * The given `url` can also be the name of a mapped url, for332 * example by default express supports "back" which redirects333 * to the _Referrer_ or _Referer_ headers or the application's334 * "home" setting. Express also supports "home" out of the box,335 * which can be set via `app.set('home', '/blog');`, and defaults336 * to '/'.337 *338 * Redirect Mapping:339 * 340 * To extend the redirect mapping capabilities that Express provides,341 * we may use the `app.redirect()` method:342 * 343 * app.redirect('google', 'http://google.com');344 * 345 * Now in a route we may call:346 *347 * res.redirect('google');348 *349 * We may also map dynamic redirects:350 *351 * app.redirect('comments', function(req, res){352 * return '/post/' + req.params.id + '/comments';353 * });354 *355 * So now we may do the following, and the redirect will dynamically adjust to356 * the context of the request. If we called this route with _GET /post/12_ our357 * redirect _Location_ would be _/post/12/comments_.358 *359 * app.get('/post/:id', function(req, res){360 * res.redirect('comments');361 * });362 *363 * Unless an absolute `url` is given, the app's mount-point364 * will be respected. For example if we redirect to `/posts`,365 * and our app is mounted at `/blog` we will redirect to `/blog/posts`.366 *367 * @param {String} url368 * @param {Number} code369 * @api public370 */371372res.redirect = function(url, status){373 var app = this.app374 , req = this.req375 , base = app.set('home') || '/'376 , status = status || 302377 , body;378379 // Setup redirect map380 var map = {381 back: req.header('Referrer', base)382 , home: base383 };384385 // Support custom redirect map386 map.__proto__ = app.redirects;387388 // Attempt mapped redirect389 var mapped = 'function' == typeof map[url]390 ? map[url](req, this)391 : map[url];392393 // Perform redirect394 url = mapped || url;395396 // Relative397 if (!~url.indexOf('://')) {398 // Respect mount-pointmisc refactorTj Holowaychukbefore adoption490584c
line 399why, one step back399 if (app.route) url = join(app.route, url);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 400–444why, one step back400401 // Absolute402 var host = req.headers.host403 , tls = req.connection.encrypted;404 url = 'http' + (tls ? 's' : '') + '://' + host + url;405 }406 407408 // Support text/{plain,html} by default409 if (req.accepts('html')) {410 body = '<p>' + http.STATUS_CODES[status] + '. Redirecting to <a href="' + url + '">' + url + '</a></p>';411 this.header('Content-Type', 'text/html');412 } else {413 body = http.STATUS_CODES[status] + '. Redirecting to ' + url;414 this.header('Content-Type', 'text/plain');415 }416417 // Respond418 this.statusCode = status;419 this.header('Location', url);420 this.end(body);421};422423/**424 * Assign the view local variable `name` to `val` or return the425 * local previously assigned to `name`.426 *427 * @param {String} name428 * @param {Mixed} val429 * @return {Mixed} val430 * @api public431 */432433res.local = function(name, val){434 this._locals = this._locals || {};435 return undefined === val436 ? this._locals[name]437 : this._locals[name] = val;438};439440/**441 * Assign several locals with the given `obj`,442 * or return the locals.443 *444 * @param {Object} objAdded `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994
line 445why, one step back445 * @return {Object|ServerResponse}connect >= 1.1.6Tj Holowaychukbefore adoption058777b
lines 446–448why, one step back446 * @api public447 */448Removed `res.helpers()` alias of `res.locals()`Tj Holowaychukbefore adoption541020f
line 449why, one step back449res.locals = function(obj){Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994
lines 450–452why, one step back450 if (0 == arguments.length) return this._locals;451 for (var key in obj) {452 this.local(key, obj[key]);connect >= 1.1.6Tj Holowaychukbefore adoption058777b
line 453why, one step back453 }Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994
line 454why, one step back454 return this;connect >= 1.1.6Tj Holowaychukbefore adoption058777b
line 455why, one step back455};