Skip to content

Commit

Permalink
fix: not sending form urlencoded properly in JS fetch snippets (#218)
Browse files Browse the repository at this point in the history
Co-authored-by: Eric Reynolds <[email protected]>
  • Loading branch information
erunion and reynolek authored Sep 3, 2021
1 parent 9530d5b commit 6b85ba2
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
12 changes: 11 additions & 1 deletion src/targets/javascript/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/output/javascript/fetch/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 6b85ba2

Please sign in to comment.