Search code examples
httpposthttpclientdeno

Http Client using HTTP POST in Deno


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.


Solution

  • 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" })
          },
        );