ladjs / superagent

Ajax for Node.js and browsers (JS HTTP client). Maintained for @forwardemail, @ladjs, @spamscanner, @breejs, @cabinjs, and @lassjs.
https://ladjs.github.io/superagent/
MIT License
16.57k stars 1.33k forks source link

[fix] qs.stringify does not serialise arrays in objects according to documentation #1798

Open MaoShizhong opened 3 months ago

MaoShizhong commented 3 months ago

Describe the bug

Node.js version: v20.10.0

OS version: Fedora 39 x86_64 (kernel 6.7.10-200)

Superagent version: 8.1.2

Description: According to the documentation, sending an object with an array value as x-www-urlencoded should encode via the form a=b&a=c (using repeat instead of indices when stringifying via qs).

Instead, it appears #1591 led to having both Node and the browser stringify using indices for arrays when passing such an object/array as the request body. This is an odd decision, as the same object passed as a query string results in stringifying without indices.

Either the query param behaviour and the documentation both change to match the Node and Client versions for the request body serialisation, or more preferably, the request body serialisation in both versions gets changed to match the current query param behaviour and documentation.

The below examples come from this request code:

const obj = { foo: ['bar', 'baz'] };
superagent
  .post('http://localhost:3000/test')
  .type('form')
  .send(obj)
  .query(obj)
  .end();

Actual behavior

actual behaviour

The object gets serialised using qs.stringify when sent as the request body via x-www-urlencoded. Despite the documentation saying this should serialise to foo=bar&foo=baz, it gets serialised using indices (default qs.stringify behaviour).

The same object is serialised without indices when used for query params, as it seems that is handled by a different qs.stringify call which does specify indices: false.

Expected behavior

desired behaviour

By changing the function used to serialise the request body in this scenario from

qs.stringify

to

(obj) => qs.stringify(obj, { indices: false })

the behaviour is now unified between request body and query params, and both now match the documentation.

Code to reproduce

https://github.com/MaoShizhong/superagent-qs-stringify-behaviour Should just be able to follow the README instructions to see behaviour and apply fix (to the node_modules superagent code).

Checklist

MaoShizhong commented 3 months ago

I presume these are the lines that would need changing to make the request body serialisation match the documentation and query param serialisation for the client version and the Node version, but I am ultimately unfamiliar with this and not sure if there are further parts that would require changing in such case.

titanism commented 3 weeks ago

PR welcome