Deno can be used to fetch data from the webserver using HTTP requests.
Deno provides the web standard
fetch API to make HTTP calls.
This chapter teaches how to make HTTP calls in your Deno program.
Deno Make HTTP Request and Display to Terminal
The following example makes a call to the URL provided as an argument in the terminal, then prints the response to the terminal.
- In the project folder hello, create a new file deno_http_request.js
Deno Live Example: deno_http_request.js
const url = Deno.args; const res = await fetch(url); const body = new Uint8Array(await res.arrayBuffer()); await Deno.stdout.write(body);
- The first part of the code gets the first argument passed to the terminal, and store it in the
- The second part of the code makes a request to the
linkvariable, which returns a promise stored in a
- After awaiting the response from the
resvariable, the third part of the code parses it as an ArrayBuffer and convert it into a Uint8Array to store in the body constant.
- The last parts of the code write it to the
stdoutwhich displays in the terminal.
Run the code
Run the code by providing a URL as the first argument:
In our case, we going to be using IP API which provides some important details about out IP. Feel free to use any URL: http://ip-api.com/csv
deno run --allow-net deno_http_request.js http://ip-api.com/csv
--allow-netflag which gives Deno permission to access the network, Deno will throw an error without this permission.
The 'Next Chapter' teaches how to handle files in Deno.
What You Should Know At The End of This Chapter
- You should be able to understand and use the
- You should be able to create and run the HTTP Request program