Skip to content
Myr

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 file

Take 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 back
1
2/*!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.send

misc refactoringTj Holowaychukbefore adoption70e6baf

lines 20–22why, one step back
20 , mime = require('mime')
21 , basename = path.basename22 , join = path.join;

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 23–62why, one step back
23
24/**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 back
63 this.charset = this.charset || 'utf-8';

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 64–73why, one step back
64 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 back
74 return this.json(body, headers, status);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 75–95why, one step back
75 }
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 headers

Fixed; ignore body on 304. Closes #701Tj Holowaychukbefore adoption9028cac

line 96why, one step back
96 if (204 == status || 304 == status) {

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 97–103why, one step back
97 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 back
104 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 back
125 var body = JSON.stringify(obj)
126 , callback = this.req.query.callback127 , jsonp = this.app.enabled('jsonp callback');128

Merge branch 'feature/res-json'Tj Holowaychukbefore adoption9e4020e

lines 129–130why, one step back
129 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 back
131
132 if (callback && jsonp) {133 this.header('Content-Type', 'text/javascript');

Revert "removed jsonp stripping"Tj Holowaychukbefore adoption60d16ea

line 134why, one step back
134 body = callback.replace(/[^\w$.]/g, '') + '(' + body + ');';

Added `res.json()` JSONP support. Closes #737Tj Holowaychukbefore adoption73ea5cd

lines 135–137why, one step back
135 }
136137 return this.send(body, headers, status);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 138–139why, one step back
138};
139

docs for res.status()Tj Holowaychukbefore adoption9477c9b

lines 140–147why, one step back
140/**
141 * Set status `code`.142 *143 * @param {Number} code144 * @return {ServerResponse}145 * @api public146 */147

Added chainable res.status(code)Tj Holowaychukbefore adoptionb04be51

lines 148–152why, one step back
148res.status = function(code){
149 this.statusCode = code;150 return this;151};152

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 153–169why, one step back
153/**
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 back
170 var next = this.req.next;

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 171–178why, one step back
171 options = options || {};
172173 // support function as second arg174 if ('function' == typeof options) {175 fn = options;176 options = {};177 }178

Fixed res.sendfile() bug preventing the transfer of files with spacesTj Holowaychukbefore adoptionc6d7608

line 179why, one step back
179 options.path = encodeURIComponent(path);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

line 180why, one step back
180 options.callback = fn;

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 181why, one step back
181 send(this.req, this, next, options);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 182–215why, one step back
182};
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 back
216 if (filename) this.contentType(filename);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

line 217why, one step back
217 this.header('Content-Disposition', filename

misc refactoringTj Holowaychukbefore adoption70e6baf

line 218why, one step back
218 ? 'attachment; filename="' + basename(filename) + '"'

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 219–224why, one step back
219 : '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 back
225 * `filename` as an attachment and optional callback `fn(err)`,
226 * and optional `fn2(err)` which is invoked when an error has

typoTj Holowaychukbefore adoption0cbb1f6

line 227why, one step back
227 * occurred after header has been sent.

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 228–231why, one step back
228 *
229 * @param {String} path230 * @param {String|Function} filename or fn231 * @param {Function} fn

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 232why, one step back
232 * @param {Function} fn2

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 233–235why, one step back
233 * @api public
234 */235

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

line 236why, one step back
236res.download = function(path, filename, fn, fn2){

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 237–240why, one step back
237 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 back
241 fn2 = fn;

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 242–247why, one step back
242 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 back
248 var sentHeader = self._header;

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

line 249why, one step back
249 if (err) {

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

lines 250–251why, one step back
250 if (!sentHeader) self.removeHeader('Content-Disposition');
251 if (sentHeader) {

misc refactorTj Holowaychukbefore adoptionaa68581

line 252why, one step back
252 fn2 && fn2(err);

Added second callback support for res.download() connection errorsTj Holowaychukbefore adoption759a57b

lines 253–259why, one step back
253 } 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 back
260 }
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} name

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

line 286why, one step back
286 * @param {Object} options

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 287–289why, one step back
287 * @api public
288 */289

Added options support to res.clearCookie()Tj Holowaychukbefore adoptiondc02b0d

lines 290–294why, one step back
290res.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 back
295};
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 back
303 * - `path` defaults to the "home" setting which is typically "/"

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 304–321why, one step back
304 *
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 back
322 if (undefined === options.path) options.path = this.app.set('home');

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 323–398why, one step back
323 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-point

misc refactorTj Holowaychukbefore adoption490584c

line 399why, one step back
399 if (app.route) url = join(app.route, url);

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 400–444why, one step back
400
401 // 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} obj

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 445why, one step back
445 * @return {Object|ServerResponse}

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

lines 446–448why, one step back
446 * @api public
447 */448

Removed `res.helpers()` alias of `res.locals()`Tj Holowaychukbefore adoption541020f

line 449why, one step back
449res.locals = function(obj){

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

lines 450–452why, one step back
450 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 back
453 }

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

line 454why, one step back
454 return this;

connect >= 1.1.6Tj Holowaychukbefore adoption058777b

line 455why, one step back
455};