Send form data with bs-fetch

2018-02-13 • 1 min read
#reasonml#bs-fetch#formData

I’m now learning ReasonML, which is a new functional programming language combining features of OCaml and JavaScript.

This article is just a note of trying bs-fetch and is a slight extension of this article. API document of bs-fetch might not be super clear if you are a beginner (and I am!). Thus, I would like to keep some notes for myself through my ReasonML learning process.

Simple examples of using bs-fetch can be seen in its repository. Here, I’m trying to send requests with some initial settings, such as headers or methods. Below is the code snippet of sending a POST request with form data and using bs-qs as helper.

let postSomethingWithFormData = (data) => {
/* suppose your data is a object with several fields. e.g.,
let data = {
"a": "aaa",
"b": 123,
"c": "kerker",
};
*/
let d = Qs.stringify(data);
Js.Promise.(
Fetch.fetchWithInit(
"http://someUrl.com",
Fetch.RequestInit.make(
~credentials=Include,
~headers=
Fetch.HeadersInit.makeWithArray([|
("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
|]),
~body=Fetch.BodyInit.make(d),
~method_=Post,
()
)
)
|> then_(Fetch.Response.json)
|> then_((rt) => Js.Promise.resolve(rt))
)
};
view raw myFetch.re hosted with ❤ by GitHub

Or, alternatively, you can try to write some simple bindings. :)

[@bs.new] external makeFormData: unit => Fetch.formData = "FormData";
[@bs.send]
external appendFormData: (Fetch.formData, string, string) => unit = "append";
let formData = makeFormData();
appendFormData(formData, "field1", "value1");
appendFormData(formData, "field2", "value2");
appendFormData(formData, "field3", "value3");
let someRequest = bodyFormData =>
Js.Promise.(
Fetch.fetchWithInit(
"https://backend.api.server",
Fetch.RequestInit.make(
~method_=Post,
~credentials=Include,
~body=Fetch.BodyInit.makeWithFormData(bodyFormData),
(),
),
)
);
view raw FormDataExample2.re hosted with ❤ by GitHub

This article is originally published on my Medium.