Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: serialize 'application/x-www-form-urlencoded' with array indices in browser #1589

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,30 +116,50 @@ function serialize(obj) {
return pairs.join('&');
}

/**
* Serialize the given `obj`, with indices for arrays.
*
* @param {Object} obj
* @return {String}
* @api private
*/

function serializeWithIndices(obj) {
if (!isObject(obj)) return obj;
const pairs = [];
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key))
pushEncodedKeyValuePair(pairs, key, obj[key], true);
}

return pairs.join('&');
}

/**
* Helps 'serialize' with serializing arrays.
* Mutates the pairs array.
*
* @param {Array} pairs
* @param {String} key
* @param {Mixed} val
* @param {Boolean} indices
*/

function pushEncodedKeyValuePair(pairs, key, val) {
function pushEncodedKeyValuePair(pairs, key, val, indices = false) {
if (val === undefined) return;
if (val === null) {
pairs.push(encodeURI(key));
return;
}

if (Array.isArray(val)) {
val.forEach((v) => {
pushEncodedKeyValuePair(pairs, key, v);
val.forEach((v, idx) => {
pushEncodedKeyValuePair(pairs, indices ? `${key}[${idx}]` : key, v, indices);
});
} else if (isObject(val)) {
for (const subkey in val) {
if (Object.prototype.hasOwnProperty.call(val, subkey))
pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, val[subkey]);
pushEncodedKeyValuePair(pairs, `${key}[${subkey}]`, val[subkey], indices);
}
} else {
pairs.push(encodeURI(key) + '=' + encodeURIComponent(val));
Expand Down Expand Up @@ -213,7 +233,7 @@ request.types = {
*/

request.serialize = {
'application/x-www-form-urlencoded': serialize,
'application/x-www-form-urlencoded': serializeWithIndices,
'application/json': safeStringify
};

Expand Down