'How to handle FormData in Miragejs?
Miragejs handles json out-of-the-box but seems to be unable to handle FormData. When I post FormData and log the received request in mirage endpoint, request.requestBody is empty.
Simplified code examples:
- POSTing FormData:
const testFile = new File(['hello'], 'hello.png', { type: 'image/png' });
const formData = new FormData('file', testFile);
fetch('https://localhost:3000/api/endpoint', {method: 'POST', body: formData});
// ...
- receiving POST in mirage mock server:
this.post('/endpoint', (schema, request) => {
console.log('request:', request);
// request.requestBody is an empty string!
});
Possibly a related issue: https://github.com/miragejs/ember-cli-mirage/issues/74
Solution 1:[1]
It's possible to cast the request.requestBody to FormData and then parse the file.
Shortening the excellent solution described in How to handle uploading and parsing files in your frontend app tests:
this.post('/endpoint', (schema, request) => {
const readFile = async (file: File): Promise<string> =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(new Error('There was an error reading the file!'));
reader.onload = () => resolve(reader.result as string);
reader.readAsText(file);
});
const formData: FormData = request.requestBody as unknown as FormData;
const uploadFile: File = formData.get('file') as File;
const fileContents: string = await readFile(uploadFile);
console.log('Uploaded file contents:', fileContents);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Juuso Ohtonen |
