multer icon indicating copy to clipboard operation
multer copied to clipboard

Added support for JSON fields for parity with Axios;

Open DigitalBrainJS opened this issue 2 years ago • 2 comments

Since v0.27.2 Axios supports FormData serializer that encodes object fields with {} ending to a JSON string. So this PR adds the ability to parse such fields by multer.

await axios.postForm('http://localhost/', {
  str: 'Jay"
  'obj{}': {x:1, foo: 'bar'},
  'files[]': document.querySelector('#myFile').files
});

Will be stored as req.body.obj

DigitalBrainJS avatar Apr 29 '22 23:04 DigitalBrainJS

I feel that this Axios-specific quirk is out of scope for Multer. Is this implemented by any other multipart parser or serialiser?

I think that this could be easily implemented as it's own middleware? Something like this:

// Multer
app.use(upload)

// Custom middleware
app.use((req, res, next) => {
  for (const key of Object.keys(req.body)) {
    if (key.endsWith('{}')) {
      req.body[key.slice(0, -2)] = JSON.parse(req.body[key])
      delete req.body[key]
    }
  }
})

That code could also be published as a package, that would work with any form-data body parser!

LinusU avatar Jun 01 '22 09:06 LinusU

@LinusU Of course, it is not difficult to make middleware that the user will have to install and configure. And yes, this is not a standard conversion, but all field conversions are based more on historical reasons than RFC. Currently, users manually use stringify/parse to pass in an object field, but IMHO it would be better if Multer handled it out of the box, because:

  • there are no other approaches to automatically process JSON in a form
  • there are no potential inconsistencies or conflicts with the current standard
  • this change does not affect performance and slightly increases the codebase
  • serialization of objects as separate Form fields using bracket notation leads to significant network traffic costs.
  • the transformation can be controlled with an option if there is any reason to turn it off
  • formed standard already uses brackets ending, so using {} fits in well with the approach. I don't see any downside to adding this conversion, since it's unlikely that someone is already using '{}' for field names. Therefore, at least it will not harm users in any way, but it may come in handy for someone.

DigitalBrainJS avatar Jun 01 '22 13:06 DigitalBrainJS

I'm sorry, but I still feel that this is out of scope for Multer. If this is something that more clients than Axios implements (especially if fetch implements it) I'd be happy to reconsider.

Thanks for taking the time to submit the PR though 🙏

LinusU avatar Oct 30 '22 14:10 LinusU