Skip to content

Commit

Permalink
JSON and JSONP default to UTF-8 in the same way as HTML. Introduces a…
Browse files Browse the repository at this point in the history
…pp.set('charset') to set charset default at the application level. Closes expressjs#632.

Signed-off-by: Tj Holowaychuk <tj@vision-media.ca>
  • Loading branch information
dshaw authored and tj committed Apr 20, 2011
1 parent ccc39e5 commit 8f054db
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 3 additions & 1 deletion lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ res.send = function(body, headers, status){
break;
case 'string':
if (!this.header('Content-Type')) {
this.charset = this.charset || 'utf-8';
this.charset = this.charset || this.app.set('charset') || 'utf-8';
this.contentType('.html');
}
break;
Expand All @@ -75,10 +75,12 @@ res.send = function(body, headers, status){
}
} else {
if (!this.header('Content-Type')) {
this.charset = this.charset || this.app.set('charset') || 'utf-8';
this.contentType('.json');
}
body = JSON.stringify(body);
if (this.req.query.callback && this.app.set('jsonp callback')) {
this.charset = this.charset || this.app.set('charset') || 'utf-8';
this.header('Content-Type', 'text/javascript');
body = this.req.query.callback.replace(/[^\w$.]/g, '') + '(' + body + ');';
}
Expand Down
12 changes: 6 additions & 6 deletions test/response.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ module.exports = {
assert.response(app,
{ url: '/bool' },
{ body: 'true'
, headers: { 'Content-Type': 'application/json' }});
, headers: { 'Content-Type': 'application/json; charset=utf-8' }});

assert.response(app,
{ url: '/html' },
Expand All @@ -76,7 +76,7 @@ module.exports = {
{ body: '{"foo":"bar"}'
, status: 201
, headers: {
'Content-Type': 'application/json'
'Content-Type': 'application/json; charset=utf-8'
, 'X-Foo': 'baz'
}});

Expand All @@ -85,15 +85,15 @@ module.exports = {
{ body: 'test({"foo":"bar"});'
, status: 201
, headers: {
'Content-Type': 'text/javascript'
'Content-Type': 'text/javascript; charset=utf-8'
, 'X-Foo': 'baz'
}});

assert.response(app,
{ url: '/jsonp?callback=baz' },
{ body: 'baz({"foo":"bar"});'
, status: 201, headers: {
'Content-Type': 'text/javascript'
'Content-Type': 'text/javascript; charset=utf-8'
, 'X-Foo': 'baz'
}});

Expand All @@ -102,7 +102,7 @@ module.exports = {
{ body: 'invalid({"foo":"bar"});'
, status: 201
, headers: {
'Content-Type': 'text/javascript'
'Content-Type': 'text/javascript; charset=utf-8'
, 'X-Foo': 'baz'
}});

Expand All @@ -111,7 +111,7 @@ module.exports = {
{ body: '{"foo":"bar"}'
, status: 201
, headers: {
'Content-Type': 'application/json'
'Content-Type': 'application/json; charset=utf-8'
, 'X-Foo': 'baz'
}});

Expand Down

0 comments on commit 8f054db

Please sign in to comment.