Skip to content

Commit d93560c

Browse files
authored
Document how to modify FormData in beforeRequest hooks (#764)
1 parent ec10a68 commit d93560c

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

readme.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,35 @@ searchParams.set('drink', 'icetea');
727727
const response = await ky.post(url, {body: searchParams});
728728
```
729729

730+
#### Modifying FormData in hooks
731+
732+
If 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`:
733+
734+
```js
735+
import ky from 'ky';
736+
737+
const response = await ky.post(url, {
738+
body: formData,
739+
hooks: {
740+
beforeRequest: [
741+
request => {
742+
const newFormData = new FormData();
743+
744+
// Modify FormData as needed
745+
for (const [key, value] of formData) {
746+
newFormData.set(key.toLowerCase(), value);
747+
}
748+
749+
// Delete `Content-Type` to let Request regenerate it with correct boundary
750+
request.headers.delete('content-type');
751+
752+
return new Request(request, {body: newFormData});
753+
}
754+
]
755+
}
756+
});
757+
```
758+
730759
### Setting a custom `Content-Type`
731760

732761
Ky 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.

0 commit comments

Comments
 (0)