Skip to content

Commit e48e31e

Browse files
committed
fix: respect enctype/formenctype HTML form attributes from form + set application/x-www-form-urlencoded as a default Content-Type for POST requests made by enhance
1 parent bf978f7 commit e48e31e

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

packages/kit/src/runtime/app/forms.js

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,13 @@ export function enhance(form_element, submit = () => {}) {
124124
: clone(form_element).action
125125
);
126126

127+
const enctype = event.submitter?.hasAttribute('formenctype')
128+
? /** @type {HTMLButtonElement | HTMLInputElement} */ (event.submitter).formEnctype
129+
: clone(form_element).enctype;
130+
127131
const form_data = new FormData(form_element);
128132

129-
if (DEV && clone(form_element).enctype !== 'multipart/form-data') {
133+
if (DEV && enctype !== 'multipart/form-data') {
130134
for (const value of form_data.values()) {
131135
if (value instanceof File) {
132136
throw new Error(
@@ -161,14 +165,29 @@ export function enhance(form_element, submit = () => {}) {
161165
let result;
162166

163167
try {
168+
const is_valid_enctype = enctype?.match(
169+
/application\/x-www-form-urlencoded|multipart\/form|text\/plain/
170+
);
171+
172+
const headers = {
173+
accept: 'application/json',
174+
'Content-Type': is_valid_enctype ? enctype : 'application/x-www-form-urlencoded',
175+
'x-sveltekit-action': 'true'
176+
};
177+
178+
// @ts-expect-error
179+
const body = enctype === 'multipart/form-data' ? form_data : new URLSearchParams(form_data);
180+
181+
if (enctype === 'multipart/form-data' && headers['Content-Type']) {
182+
// @ts-expect-error
183+
delete headers['Content-Type'];
184+
}
185+
164186
const response = await fetch(action, {
165187
method: 'POST',
166-
headers: {
167-
accept: 'application/json',
168-
'x-sveltekit-action': 'true'
169-
},
188+
headers,
170189
cache: 'no-store',
171-
body: form_data,
190+
body,
172191
signal: controller.signal
173192
});
174193

0 commit comments

Comments
 (0)