Skip to content
Myr

Document how to modify `FormData` in `beforeRequest` hooks (#764)

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 ec10a68 · Browse files · 1 file+29 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+29 added−0 removed

  • other:+29 added−0 removed

1 file+29 added−0 removed

modified:readme.md+29 added
725 unmodified lines
726727const response = await ky.post(url, {body: searchParams});728```729730#### Modifying FormData in hooks731732If you need to modify FormData in a `beforeRequest` hook (for example, to transform field names), delete the `Content-Type` header before creating a new `Request`:733734```js735import ky from 'ky';736737const response = await ky.post(url, {738 body: formData,739 hooks: {740 beforeRequest: [741 request => {742 const newFormData = new FormData();743744 // Modify FormData as needed745 for (const [key, value] of formData) {746 newFormData.set(key.toLowerCase(), value);747 }748749 // Delete `Content-Type` to let Request regenerate it with correct boundary750 request.headers.delete('content-type');751752 return new Request(request, {body: newFormData});753 }754 ]755 }756});757```758759### Setting a custom `Content-Type`760761Ky automatically sets an appropriate [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such as `application/x-amz-json-1.1`. Using the `headers` option, you can manually override the content type.762
108 unmodified lines