node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7.05k stars 682 forks source link

Top-level JSON arrays are interpreted as objects #760

Closed Rush closed 3 years ago

Rush commented 3 years ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

const http = require('http');
const formidable = require('formidable');

const server = http.createServer((req, res) => {
  const form = formidable({ multiples: true });

  form.parse(req, (err, fields, files) => {
    if (err) {
      res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
      res.end(String(err));
      return;
    }
    console.log('Got fields', fields);
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ fields, files }, null, 2));
  });
});

server.listen(9090, async () => {
  const res = await require('node-fetch')('http://localhost:9090/post', { method: 'POST', headers: { "Content-Type": "application/json" }, body: `[{ "foo": "bar" } ]` });
  console.log('Res', await res.json());
  process.exit(0);
});

What was the result you got?

JSON top-level array was interpreted as an object with '0' as key.

» node index.js
Got fields { '0': { foo: 'bar' } }
Res { fields: { '0': { foo: 'bar' } }, files: {} }

What result did you expect?

Expected to receive an array. Arrays shouldn't be interpreted as objeccts.

Got fields [ { foo: 'bar' } ]
GrosSacASac commented 3 years ago

Yes, also top level numbers and strings are not supported I think

Rush commented 3 years ago

Not sure if numbers and strings are universally considered valid JSON but top-level arrays definitely are as per this SO answer https://stackoverflow.com/a/3833312 which links to respective RFCs.

GrosSacASac commented 3 years ago

json.org also and every JS implementation