Skip to content
Transform an object/collection to FormData.
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.editorconfig
.eslintrc.json
.gitignore
.huskyrc.json
.lintstagedrc
.npmignore
.size-limit.js
.travis.yml
form-data-browser.js
form-data.js
isPlainObject.js
license
package.json
readme.md
serialize.d.ts
serialize.js
test.js
yarn.lock

readme.md

object-to-form-data

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

dependencies Status devDependencies Status Build Status Code Coverage

API

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

  • {object} object – Object to transform
  • {object | string | 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.
    • {string} [root = null] – Just a root key of all fieldnames

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."
      }
    ]
  }
}

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

const options = {
  method: "POST", body
}

const onResponse = res => res.json()

const onData = data => console.log(data)

const onError = err => console.error(err)

fetch("https://api.whatever.co/ping", options)
  .then(onResponse).then(onData, onError)

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

You can’t perform that action at this time.