node-http-proxy
node-http-proxy copied to clipboard
Content-type Header Not Handled Correctly for JSON and Form Data with Charset Information
Description
In the file bodyDecoder-middleware.js, lines 47-53, the server incorrectly handles Content-type: application/json; charset=utf-8 headers and similarly formatted headers for form data (application/x-www-form-urlencoded). The existing code uses strict string comparison, causing issues when the Content-type header contains additional properties like charset.
Existing Code
// bodyDecoder-middleware.js, lines 47-53
if (contentType === 'application/json') {
bodyData = JSON.stringify(req.body);
}
if (contentType === 'application/x-www-form-urlencoded') {
bodyData = queryString.stringify(req.body);
}
This code only works for requests that send a pure Content-type: application/json or Content-type: application/x-www-form-urlencoded without any additional properties like charset.
Expected behavior
The code should be able to handle Content-type headers with additional parameters.
Standard Practice According to MDN
According to MDN's documentation on Content-Type, the header can contain additional parameters (like charset), separated by a semicolon. Therefore, using startsWith would align better with this standard practice.
Solution
A possible solution is to change the string comparison to check if the Content-type starts with the desired value. Below is the proposed change:
if (contentType.startsWith('application/json')) {
bodyData = JSON.stringify(req.body);
}
if (contentType.startsWith('application/x-www-form-urlencoded')) {
bodyData = queryString.stringify(req.body);
}
Steps to Reproduce
- Send a POST request with a
Content-type: application/json; charset=utf-8header and JSON payload. - Observe that the existing code does not handle the body as expected.
Thank you for taking the time to look into this issue.