Http Client using HTTP POST in Deno

Viewed 1905

I would like to write a http client in Deno using an HTTP POST. Is this possible in Deno at this time?

For reference, is an example of doing an http GET in Deno:

const response = await fetch("<URL>");

I looked at the HTTP module in Deno and it appears to be focused on server side only at this time.

2 Answers

To do a multipart/form-data POST, form post data can be packaged using the FormData object. Here is a client side example for sending form data over HTTP POST:

    // deno run --allow-net http_client_post.ts
    const form = new FormData();
    form.append("field1", "value1");
    form.append("field2", "value2");
    const response = await fetch("http://localhost:8080", {
        method: "POST",
        headers: { "Content-Type": "multipart/form-data" },
        body: form 
    });
    
    console.log(response)

Update 2020-07-21:

As per answer from @fuglede, to send JSON over HTTP POST:

    const response = await fetch(
      url,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ field1: "value1", field2: "value2" })
      },
    );

The other answer is useful for multipart/form-data-encoded data, but it's worth noting that the same approach can be used to submit data of other encodings as well. For instance, to POST JSON data, you can just use a string for the body argument, which ends up looking something like the below:

const messageContents = "Some message";
const body = JSON.stringify({ message: messageContents });
const response = await fetch(
  url,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: body,
  },
);
Related