@octetstream/object-to-form-data

Serialize given object/collection to a FormData.

Usage no npm install needed!

<script type="module">
  import octetstreamObjectToFormData from 'https://cdn.skypack.dev/@octetstream/object-to-form-data';
</script>

README

object-to-form-data

Transform an object/collection to FormData. Good to use with then-busboy

Code Coverage CI ESLint

API

serialize(object[, options]) -> {FormData}

  • {object} object – Object to transform
  • {object | boolean} options – Serialization options. This argument might be an object with "root" and "strict" parameters. Or you can pass one of them as the second argument:
    • {boolean} [strict = false] – if set to true, all false boolean values will be omitted.

Usage

import serialize from "@octetstream/object-to-form-data"

const object = {
  message: {
    sender: "Glim Glam",
    text: "Can you believe it, Trixie?",
    attachments: [
      {
        file: File, // this field will be represented as a window.File instance
        description: "I beat Twilight Sparkle and all I got was this lousy t-shirt."
      }
    ]
  }
}

const options = {
  method: "post",

  // You will receive a FormData instance with all fields of given object
  body: serialize(object)
}

const response = await fetch("https://httpbin.org/post", options)

Important! If you're using this library in Node.js, you also need the formdata-node package to serialize your objects/collections. See documentation of this implementation to learn how to send queries with that implementation.