How to make an HTTP request in Deno
In this tutorial, we are going to learn about how to make an http request and fetch data from the API in Deno.
Making an HTTP request
We can use the fetch()
API to make an http request in deno.
The fetch()
api is available in the global scope, so that we don’t need any special imports.
Example:
const res = await fetch("https://reqres.in/api/users/1");
const user = await res.json();
console.log(user);
In the above code, we first send an http
request to the reqres.in
api, await for the response, and stored it in the res
variable.
On line 2, we are parsing our response
body into a JSON object using res.json()
method.
On line 3, we are logging the user
data inside the console.
Now, run the program.
deno run app.js
You will see the following error.
error: Uncaught PermissionDenied: network access to "https://reqres.in/api/users/1",
run again with the --allow-net flag
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async fetch ($deno$/web/fetch.ts:265:27)
at async file:///Users/saigowtham/Desktop/deno-p/app.js:1:14
This error has occurred because we didn’t give network access permission to the deno.
Now, run the program again by giving a network access permission using --allow-net
flag.
deno run --allow-net=reqres.in app.js
Output:
{
data: {
id: 1,
email: "george.bluth@reqres.in",
first_name: "George",
last_name: "Bluth",
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
},
ad: {
company: "StatusCode Weekly",
url: "http://statuscode.org/",
text: "A weekly newsletter focusing on the server, performance, etc"
}
}