Support non-ASCII values in headers by auto-encoding them

Include a flag header indicating the auto-encoding occurred

Fixes https://github.com/bigskysoftware/htmx/issues/191
This commit is contained in:
carson 2020-09-10 12:40:25 -06:00
parent 7cc8f08377
commit a890abf626
2 changed files with 22 additions and 9 deletions

View File

@ -1476,6 +1476,18 @@ return (function () {
addExpressionVars(parentElt(elt), rawParameters);
}
function safelySetHeaderValue(xhr, header, headerValue) {
if (headerValue !== null) {
try {
xhr.setRequestHeader(header, headerValue);
} catch (e) {
// On an exception, try to set the header URI encoded instead
xhr.setRequestHeader(header, encodeURIComponent(headerValue));
xhr.setRequestHeader(header + "-URI-AutoEncoded", "true");
}
}
}
function issueAjaxRequest(elt, verb, path, eventTarget) {
var target = getTarget(elt);
if (target == null) {
@ -1569,7 +1581,8 @@ return (function () {
// request headers
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
if (headers[header] !== null) xhr.setRequestHeader(header, headers[header]);
var headerValue = headers[header];
safelySetHeaderValue(xhr, header, headerValue);
}
}

View File

@ -1,12 +1,4 @@
describe("Core htmx internals Tests", function() {
beforeEach(function () {
this.server = makeServer();
clearWorkArea();
});
afterEach(function () {
this.server.restore();
clearWorkArea();
});
it("makeFragment works with janky stuff", function(){
htmx._("makeFragment")("<html></html>").tagName.should.equal("BODY");
@ -20,4 +12,12 @@ describe("Core htmx internals Tests", function() {
htmx._("makeFragment")("<tr></tr>").tagName.should.equal("TBODY");
})
it("set header works with non-ASCII values", function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "/dummy");
htmx._("safelySetHeaderValue")(xhr, "Example", "привет");
// unfortunately I can't test the value :/
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
})
});