fix-request-body.js 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.fixRequestBody = void 0;
  4. const querystring = require("querystring");
  5. /**
  6. * Fix proxied body if bodyParser is involved.
  7. */
  8. function fixRequestBody(proxyReq, req) {
  9. // skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
  10. if (req.readableLength !== 0) {
  11. return;
  12. }
  13. const requestBody = req.body;
  14. if (!requestBody) {
  15. return;
  16. }
  17. const contentType = proxyReq.getHeader('Content-Type');
  18. if (!contentType) {
  19. return;
  20. }
  21. const writeBody = (bodyData) => {
  22. // deepcode ignore ContentLengthInCode: bodyParser fix
  23. proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
  24. proxyReq.write(bodyData);
  25. };
  26. if (contentType.includes('application/json')) {
  27. writeBody(JSON.stringify(requestBody));
  28. }
  29. else if (contentType.includes('application/x-www-form-urlencoded')) {
  30. writeBody(querystring.stringify(requestBody));
  31. }
  32. }
  33. exports.fixRequestBody = fixRequestBody;