Make HTTP Get request in Deno

0
1292
Make HTTP Get request in Deno
Make HTTP Get request in Deno

It is easy to make HTTP Get request in Deno. I will show you how to do it in this post.

To perform HTTP Get request in Deno, we will use fetch() function, this is identical to fetch function in Javascript which can be called in any modern browsers and NodeJS.

Take a look at this example:

const res = await fetch("https://ifconfig.me/all.json");

const data = await res.text();

console.log(data);

To execute, we will need to provide network permission which is the --allow-net flag.

$ deno run --allow-net main.ts
{
  "ip_addr": "XXX.XXX.XXX.XXX",
  "remote_host": "unavailable",
  "user_agent": "Deno/1.23.3",
  "port": 53420,
  "language": "*",
  "method": "GET",
  "encoding": "gzip, br",
  "mime": "*/*",
  "via": "1.1 google",
  "forwarded": "XXX.XXX.XXX.XXX, XXX.XXX.XXX.XXX,Y.Y.Y.Y"
}

To get response data in JSON format, we can call response.json() instead of response.text().

const res = await fetch("https://ifconfig.me/all.json");

const data = await res.json(); // get response data in JSON format

console.log(data);

You can also provide headers for the request, like this:

const res = await fetch("https://ifconfig.me/all.json", {
    headers: {
        "User-Agent": "Pete Browser/1.0.1"
    }
});

const data = await res.json();

console.log(data);

That’s how you make HTTP Get request in Deno.

Have fun!