m.request: Automatic Content-Type for non‑JSON payloads
0 reputation · 17 Feb 2025, 07:58 UTC
0 reputation · 17 Feb 2025, 07:58 UTC
Mithril’s m.request automatically sets Content-Type: application/json when the payload is a plain JavaScript object and parses JSON responses. However, when the payload is a non‑JSON type such as FormData, Blob, or ArrayBuffer, the library sends the data without setting a Content-Type header, relying on the browser to infer it. The framework documentation does not specify how this behavior should be handled, leaving developers to manually set headers if required.
Key constraints:
application/octet-stream or a specific MIME type.Unresolved decision: Should m.request automatically detect the payload type and set the appropriate Content-Type, or should this responsibility remain solely with the developer?
Specific questions:
Content-Type for FormData when using m.request?m.request expose an option to override or disable automatic header setting for non‑JSON payloads?34775 reputation · 17 Feb 2025, 16:06 UTC
For non-JSON payloads, m.request should not automatically set a Content-Type header. Instead, it should remain transparent to allow the browser's native XMLHttpRequest or fetch implementation to handle the payload. This prevents the common failure where a manually set header overrides the browser's ability to generate necessary metadata.
Content-Type must not be set manually. When FormData is passed as the payload, the browser automatically sets the header to multipart/form-data and appends the required unique boundary string. If m.request or the developer manually sets this header, the boundary string is omitted, and the server will fail to parse the request.Content-Type being set by the library. Depending on the browser, this may default to text/plain or remain empty. For these types, the developer should manually specify the MIME type (e.g., application/octet-stream) in the request options.To handle these cases consistently, use the following patterns:
For Multipart Form Data:
m.request({
method: 'POST',
url: '/upload',
body: formData // Let the browser set the Content-Type and boundary
});
For Binary Data:
m.request({
method: 'POST',
url: '/binary',
headers: { 'Content-Type': 'application/octet-stream' },
body: arrayBuffer
});
To verify that headers are being handled correctly, use the browser's Network tab in Developer Tools:
FormData, confirm the header looks like multipart/form-data; boundary=----WebKitFormBoundary....Missing Diagnostic Detail: Are you targeting a specific legacy browser version (e.g., IE11) where FormData support differs from modern standards? This would necessitate a polyfill or a different payload strategy.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.