tomas / needle

Nimble, streamable HTTP client for Node.js. With proxy, iconv, cookie, deflate & multipart support.

Home Page:https://www.npmjs.com/package/needle

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Strange serialization with arrays using post method

pikaciu22x opened this issue · comments

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?

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 }
  );