tomas / needle

Nimble, streamable HTTP client for Node.js. With proxy, iconv, cookie, deflate & multipart support.
https://www.npmjs.com/package/needle
MIT License
1.63k stars 236 forks source link

Strange serialization with arrays using post method #384

Closed pikaciu22x closed 2 years ago

pikaciu22x commented 2 years ago

Hey team,

I stumbled upon a strange body serialization error. When body includes an array, internal array properties get merged together. The issue can be reproduced with the following snippet:

const needle = require('needle');
const express = require('express');

const router = express.Router();

router.post('/receiver', (req, res) => {
  console.log('WRONG BODY', JSON.stringify(req.body));

  return res.status(200).json({});
});

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(router);

const send = async () => {
  await needle(
    'post',
    'http://localhost:3333/receiver',
    {
      acl: [
        { prop1: 'test', arrayProp: ['a', 'b'] },
        { prop1: 'test2', arrayProp: ['c', 'd'] },
      ],
    },
    { headers: { 'tes-test': 'test' } }
  );
};

app.listen(3333, () => {
  console.log('started');
  send();
});

output: WRONG BODY {"acl":[{"prop1":["test","test2"],"arrayProp":["a","b","c","d"]}]}

nodejs version: 14 needle version: 3.0.0 ( same with 2.*.*)

maybe i'm doing something wrong?

pikaciu22x commented 2 years ago

for anyone like me, answering my own question:

maybe i'm doing something wrong?

yes.

I was missing json: true in the options. So the request should look like this:

await needle(
    'post',
    'http://localhost:3333/receiver',
    {
      acl: [
        { prop1: 'test', arrayProp: ['a', 'b'] },
        { prop1: 'test2', arrayProp: ['c', 'd'] },
      ],
    },
    { headers: { 'tes-test': 'test' }, json: true }
  );