node-http-proxy icon indicating copy to clipboard operation
node-http-proxy copied to clipboard

Content-type Header Not Handled Correctly for JSON and Form Data with Charset Information

Open ManuelLoaizaV opened this issue 2 years ago • 0 comments
trafficstars

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

  1. Send a POST request with a Content-type: application/json; charset=utf-8 header and JSON payload.
  2. Observe that the existing code does not handle the body as expected.

Thank you for taking the time to look into this issue.

ManuelLoaizaV avatar Aug 25 '23 21:08 ManuelLoaizaV