If Meteor.http.call JSON-ifies the request body, default the Content-Type to

application/json.

This matches our heuristic for deciding whether to parse responses as JSON.
This commit is contained in:
David Glasser
2012-12-28 15:58:41 -08:00
parent 297f20d0d8
commit 3bada2a9f9
3 changed files with 28 additions and 8 deletions

View File

@@ -20,9 +20,13 @@ Meteor.http = Meteor.http || {};
method = (method || "").toUpperCase();
var headers = {};
var content = options.content;
if (options.data)
if (options.data) {
content = JSON.stringify(options.data);
headers['Content-Type'] = 'application/json';
}
var params_for_url, params_for_body;
if (content || method === "GET" || method === "HEAD")
@@ -51,6 +55,8 @@ Meteor.http = Meteor.http || {};
content = Meteor.http._encodeParams(params_for_body);
}
_.extend(headers, options.headers || {});
////////// Callback wrapping //////////
// wrap callback to always return a result object, and always
@@ -84,9 +90,8 @@ Meteor.http = Meteor.http || {};
xhr.open(method, url, true, username, password);
if (options.headers)
for (var k in options.headers)
xhr.setRequestHeader(k, options.headers[k]);
for (var k in headers)
xhr.setRequestHeader(k, headers[k]);
// setup timeout

View File

@@ -27,9 +27,13 @@ Meteor.http = Meteor.http || {};
var url_parts = url_util.parse(url);
var headers = {};
var content = options.content;
if (options.data)
if (options.data) {
content = JSON.stringify(options.data);
headers['Content-Type'] = 'application/json';
}
var params_for_url, params_for_body;
@@ -42,9 +46,6 @@ Meteor.http = Meteor.http || {};
url_parts.protocol+"//"+url_parts.host+url_parts.pathname,
url_parts.search, options.query, params_for_url);
var headers = {};
if (options.auth) {
if (options.auth.indexOf(':') < 0)
throw new Error('auth option should be of the form "username:password"');

View File

@@ -222,6 +222,20 @@ testAsyncMulti("httpcall - methods", [
test.equal(result.statusCode, 200);
var data = result.data;
test.equal(data.body, {greeting: "Hello World!"});
test.equal(data.headers['content-type'], 'application/json');
}));
Meteor.http.call(
"POST", url_prefix()+"/data-test-explicit",
{ data: {greeting: "Hello World!"},
headers: {'Content-Type': 'text/stupid'} },
expect(function(error, result) {
test.isFalse(error);
test.isTrue(result);
test.equal(result.statusCode, 200);
var data = result.data;
test.equal(data.body, {greeting: "Hello World!"});
test.equal(data.headers['content-type'], 'text/stupid');
}));
}
]);