Allow user to override Content-Type header (#1906)

* allow user to override Content-Type header

* reorder the code so it won't use userSetContentType variable

* remove userSetContentType

* clarification

* remove unrelated changes

---------

Co-authored-by: gbourant <root@gbourant.com>
This commit is contained in:
gbourant 2023-11-16 22:42:45 +02:00 committed by GitHub
parent d7735ad645
commit 6a9a861ad9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 4 deletions

View File

@ -3111,6 +3111,11 @@ return (function () {
var headers = getHeaders(elt, target, promptResponse);
if (verb !== 'get' && !usesFormData(elt)) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (etc.headers) {
headers = mergeObjects(headers, etc.headers);
}
@ -3124,10 +3129,6 @@ return (function () {
var allParameters = mergeObjects(rawParameters, expressionVars);
var filteredParameters = filterValues(allParameters, elt);
if (verb !== 'get' && !usesFormData(elt)) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (htmx.config.getCacheBusterParam && verb === 'get') {
filteredParameters['org.htmx.cache-buster'] = getRawAttribute(target, "id") || "true";
}

View File

@ -273,6 +273,44 @@ describe("Core htmx API test", function(){
div.innerHTML.should.equal("Clicked!");
});
it('ajax api Content-Type header is application/x-www-form-urlencoded', function(){
this.server.respondWith("POST", "/test", function (xhr) {
var params = getParameters(xhr);
xhr.requestHeaders['Content-Type'].should.equal('application/x-www-form-urlencoded;charset=utf-8');
params['i1'].should.equal("test");
xhr.respond(200, {}, "Clicked!")
});
var div = make("<div id='d1'></div>");
htmx.ajax("POST", "/test", {target:"#d1", values:{i1: 'test'}})
this.server.respond();
div.innerHTML.should.equal("Clicked!");
});
it('ajax api Content-Type header override to application/json', function(){
this.server.respondWith("POST", "/test", function (xhr) {
var params = getParameters(xhr);
xhr.requestHeaders['Content-Type'].should.equal('application/json;charset=utf-8');
params['i1'].should.equal("test");
xhr.respond(200, {}, "Clicked!");
});
var div = make("<div id='d1'></div>");
htmx.ajax('POST',"/test", {
target:'#d1',
swap:'innerHTML',
headers: {
'Content-Type': 'application/json'
},
values:{i1: 'test'}
})
this.server.respond();
div.innerHTML.should.equal("Clicked!");
});
it('can re-init with new attributes', function () {
this.server.respondWith("PATCH", "/test", "patch");
this.server.respondWith("DELETE", "/test", "delete");