From 6b85ba24b13241990fecae20eeae3c7d257cd415 Mon Sep 17 00:00:00 2001 From: Jon Ursenbach Date: Fri, 3 Sep 2021 13:31:01 -0700 Subject: [PATCH] fix: not sending form urlencoded properly in JS fetch snippets (#218) Co-authored-by: Eric Reynolds --- src/targets/javascript/fetch.js | 12 +++++++++++- .../javascript/fetch/application-form-encoded.js | 2 +- test/fixtures/output/javascript/fetch/full.js | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/targets/javascript/fetch.js b/src/targets/javascript/fetch.js index 2bf213fd7..f76e396cb 100644 --- a/src/targets/javascript/fetch.js +++ b/src/targets/javascript/fetch.js @@ -67,7 +67,17 @@ module.exports = function (source, options) { } } - code.push('const options = %s;', stringifyObject(options, { indent: opts.indent, inlineCharacterLimit: 80 })) + code.push('const options = %s;', stringifyObject(options, { + indent: opts.indent, + inlineCharacterLimit: 80, + transform: (object, property, originalResult) => { + if (property === 'body' && source.postData.mimeType === 'application/x-www-form-urlencoded') { + return `new URLSearchParams(${originalResult})` + } + + return originalResult + } + })) .blank() if (source.postData.mimeType === 'multipart/form-data') { diff --git a/test/fixtures/output/javascript/fetch/application-form-encoded.js b/test/fixtures/output/javascript/fetch/application-form-encoded.js index 186c1dbc5..a710c45c1 100644 --- a/test/fixtures/output/javascript/fetch/application-form-encoded.js +++ b/test/fixtures/output/javascript/fetch/application-form-encoded.js @@ -1,7 +1,7 @@ const options = { method: 'POST', headers: {'content-type': 'application/x-www-form-urlencoded'}, - body: {foo: 'bar', hello: 'world'} + body: new URLSearchParams({foo: 'bar', hello: 'world'}) }; fetch('http://mockbin.com/har', options) diff --git a/test/fixtures/output/javascript/fetch/full.js b/test/fixtures/output/javascript/fetch/full.js index 4c7d08f18..99298d460 100644 --- a/test/fixtures/output/javascript/fetch/full.js +++ b/test/fixtures/output/javascript/fetch/full.js @@ -5,7 +5,7 @@ const options = { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' }, - body: {foo: 'bar'} + body: new URLSearchParams({foo: 'bar'}) }; fetch('http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value', options)