From f46b8c92388ec3c24c474728a5b544e40ed173a9 Mon Sep 17 00:00:00 2001 From: Leo Horie Date: Thu, 26 Jun 2014 16:32:05 -0400 Subject: [PATCH] auto-send Content-Type header if using JSON.stringify as serialize in m.request --- mithril.js | 7 +++++-- tests/mithril-tests.js | 7 +++++++ tests/mock.js | 4 ++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/mithril.js b/mithril.js index a8cf5f22..9df7f567 100644 --- a/mithril.js +++ b/mithril.js @@ -561,6 +561,9 @@ Mithril = m = new function app(window) { else options.onerror({type: "error", target: xhr}) } } + if (options.serialize == JSON.stringify && options.method != "GET") { + xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); + } if (typeof options.config == "function") { var maybeXhr = options.config(xhr, options) if (maybeXhr !== undefined) xhr = maybeXhr @@ -592,8 +595,8 @@ Mithril = m = new function app(window) { m.request = function(xhrOptions) { if (xhrOptions.background !== true) m.startComputation() var deferred = m.deferred() - var serialize = xhrOptions.serialize || JSON.stringify - var deserialize = xhrOptions.deserialize || JSON.parse + var serialize = xhrOptions.serialize = xhrOptions.serialize || JSON.stringify + var deserialize = xhrOptions.deserialize = xhrOptions.deserialize || JSON.parse var extract = xhrOptions.extract || function(xhr) { return xhr.responseText.length === 0 && deserialize === JSON.parse ? null : xhr.responseText } diff --git a/tests/mithril-tests.js b/tests/mithril-tests.js index d720a671..9568e988 100644 --- a/tests/mithril-tests.js +++ b/tests/mithril-tests.js @@ -1211,6 +1211,13 @@ function testMithril(mock) { m.endComputation() return prop() === undefined && error() === "no error" && exception.message == "error occurred" }) + test(function() { + var error = m.prop("no error") + var prop = m.request({method: "POST", url: "test"}).then(null, error) + var xhr = mock.XMLHttpRequest.$instances.pop() + xhr.onreadystatechange() + return xhr.$headers["Content-Type"] == "application/json; charset=utf-8" + }) //m.deferred test(function() { diff --git a/tests/mock.js b/tests/mock.js index f39b3d6d..68797241 100644 --- a/tests/mock.js +++ b/tests/mock.js @@ -85,6 +85,10 @@ mock.window = new function() { } window.XMLHttpRequest = new function() { var request = function() { + this.$headers = {} + this.setRequestHeader = function(key, value) { + this.$headers[key] = value + } this.open = function(method, url) { this.method = method this.url = url