Fix FormData `content-type` boundary regeneration when retrying in hooks (#752)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 019e10e · Browse files · 2 files·+69 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+69 added−8 removed
- tests:+58 added−0 removed
- other:+11 added−8 removed
Provenance
- Commit
d02b636- Tree
938e000- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
019e10e
2 files changed+69 added−8 removed
modified:source/core/Ky.ts+11 added-8 removed
213 unmodified lines214 this._options.body = this._options.stringifyJson?.(this._options.json) ?? JSON.stringify(this._options.json);215 this._options.headers.set('content-type', this._options.headers.get('content-type') ?? 'application/json');216 }217 218+ // To provide correct form boundary, Content-Type header should be deleted when creating Request from another Request with FormData/URLSearchParams body219+ // Only delete if user didn't explicitly provide a custom content-type220+ const userProvidedContentType = options.headers && new globalThis.Headers(options.headers as HeadersInit).has('content-type');221+ if (222+ this._input instanceof globalThis.Request223+ && ((supportsFormData && this._options.body instanceof globalThis.FormData) || this._options.body instanceof URLSearchParams)224+ && !userProvidedContentType225+ ) {226+ this._options.headers.delete('content-type');227+ }228+229 this.request = new globalThis.Request(this._input, this._options);230 231 if (hasSearchParameters(this._options.searchParams)) {232 // eslint-disable-next-line unicorn/prevent-abbreviations3 unmodified lines236 // eslint-disable-next-line unicorn/prevent-abbreviations237 const searchParams = '?' + textSearchParams;238 const url = this.request.url.replace(/(?:\?.*?)?(?=#|$)/, searchParams);239 229- // To provide correct form boundary, Content-Type header should be deleted each time when new Request instantiated from another one230- if (231- ((supportsFormData && this._options.body instanceof globalThis.FormData)232- || this._options.body instanceof URLSearchParams) && !(this._options.headers && (this._options.headers as Record<string, string>)['content-type'])233- ) {234- this.request.headers.delete('content-type');235- }236-240 // The spread of `this.request` is required as otherwise it misses the `duplex` option for some reason and throws.241 this.request = new globalThis.Request(new globalThis.Request(url, {...this.request}), this._options as RequestInit);242 }243 122 unmodified linesmodified:test/formdata-searchparams.ts+58 added
53 unmodified lines5455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411553 unmodified lines t.is(lastProgress, 1, 'Final progress should be 100%');
await server.close();});
test('retries with FormData in afterResponse hook maintains correct boundary', async t => { const server = await createHttpTestServer();
let requestCount = 0; const receivedBoundaries: string[] = [];
server.post('/', (request, response) => { requestCount++;
const contentType = request.headers['content-type'] ?? ''; const boundaryMatch = /boundary=([^;]+)/.exec(contentType); const headerBoundary = boundaryMatch?.[1];
let body = ''; request.on('data', chunk => { body += chunk.toString(); // eslint-disable-line @typescript-eslint/restrict-plus-operands });
request.on('end', () => { // Extract boundary from actual body content const bodyBoundaryMatch = /^--([^\r\n]+)/.exec(body); const bodyBoundary = bodyBoundaryMatch?.[1];
receivedBoundaries.push(`header:${headerBoundary},body:${bodyBoundary}`);
if (requestCount === 1) { // First request fails with 401 response.status(401).end(); } else { // Second request succeeds - verify boundary matches const boundariesMatch = headerBoundary === bodyBoundary; response.json({success: boundariesMatch}); } }); });
const formData = new FormData(); formData.append('field', 'value');
const result = await ky.post(server.url, { body: formData, hooks: { afterResponse: [ async (request, options, response) => { if (response.status === 401) { return ky(request, options); } }, ], }, }).json<{success: boolean}>();
t.is(requestCount, 2, 'Should make 2 requests'); t.true(result.success, 'Content-type boundary should match body boundary on retry');
await server.close();});