Make HTTP Post request in Deno

0
2111
Make HTTP Post request in Deno
Make HTTP Post request in Deno

In this post, I will show you how to make HTTP Post request in Deno.

Similar to Javascript, Deno uses fetch() function to make HTTP requests for all the verb by default.

To make POST request with JSON data:

const postData = {
    "name": "Pete Houston",
    "title": "Make HTTP Post request in Deno",
    "year": 2022,
};

const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify(postData),
})

console.log(`Status: ${res.status}`);

const data = await res.json();

console.log(`Body: ${JSON.stringify(data)}`);

To execute, we need to provide --allow-net flag:

$ deno run --allow-net main.ts
Status: 201
Body: {"name":"Pete Houston","title":"Make HTTP Post request in Deno","year":2022,"id":101}

To make HTTP Post request for form data, we will use FormData for the body:

const formData = new FormData();
formData.append("name", "Pete Houston");
formData.append("title", "Make HTTP Post request in Deno");
formData.append("year", "2022");

const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    body: formData,
});

That’s how to make HTTP Post request in Deno.

Have fun!