From 7fc0e0378cfb7750b5f5631c0583817089d19961 Mon Sep 17 00:00:00 2001 From: cetra3 Date: Fri, 30 Dec 2016 17:03:13 +1030 Subject: [PATCH] Allow Request Headers to be set via config (#1464) Fixes #1463. --- mithril.d.ts | 5 +++++ mithril.js | 8 ++++++++ test/mithril.request.js | 26 ++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/mithril.d.ts b/mithril.d.ts index 72c451b3..5bda5d4b 100644 --- a/mithril.d.ts +++ b/mithril.d.ts @@ -840,6 +840,11 @@ declare namespace Mithril { */ password?: string; + /** + * An optional object map of headers with their respective values + */ + headers?: {[key: string]: string}; + /** * An optional function to run between `open` and `send`, useful for * adding request headers or using XHR2 features such as the `upload` diff --git a/mithril.js b/mithril.js index 42c5963b..579e5222 100644 --- a/mithril.js +++ b/mithril.js @@ -2171,6 +2171,14 @@ if (maybeXhr != null) xhr = maybeXhr } + if (isObject(options.headers)) { + for (var header in options.headers) { + if (hasOwn.call(options.headers, header)) { + xhr.setRequestHeader(header, options.headers[header]) + } + } + } + var data = options.method === "GET" || !options.data ? "" : options.data if (data && !isString(data) && data.constructor !== global.FormData) { diff --git a/test/mithril.request.js b/test/mithril.request.js index c8a3662a..8ccac1ea 100644 --- a/test/mithril.request.js +++ b/test/mithril.request.js @@ -146,6 +146,32 @@ describe("m.request()", function () { expect(xhr.$headers).to.not.have.property("Content-Type") }) + + it("sets xhr request headers as per the headers config", function () { + var error = m.prop() + + m.request({ + method: "POST", + url: "test", + headers: { + "Authorization" : "Bearer 12345abcd12345", + "CustomHeader" : "CustomValue" + } + }).then(null, error) + + var xhr = mock.XMLHttpRequest.$instances.pop() + xhr.onreadystatechange() + + expect(xhr.$headers).to.have.property( + "Authorization", + "Bearer 12345abcd12345") + + expect(xhr.$headers).to.have.property( + "CustomHeader", + "CustomValue") + }) + + it("correctly sets initial value", function () { var prop = m.request({ method: "POST",