Fetch data

Concepts

  • Like browsers, Deno implements web standard APIs such as fetch.
  • Deno is secure by default, meaning explicit permission must be granted to access the network.
  • See also: Deno’s permissions model.

Overview

When building any sort of web application developers will usually need to retrieve data from somewhere else on the web. This works no differently in Deno than in any other JavaScript application, just call the the fetch() method. For more information on fetch read the MDN documentation.

The exception with Deno occurs when running a script which makes a call over the web. Deno is secure by default which means access to IO (Input / Output) is prohibited. To make a call over the web Deno must be explicitly told it is ok to do so. This is achieved by adding the --allow-net flag to the deno run command.

Example

Command: deno run --allow-net fetch.ts

  1. /**
  2. * Output: JSON Data
  3. */
  4. const json = fetch("https://api.github.com/users/denoland");
  5. json.then((response) => {
  6. return response.json();
  7. }).then((jsonData) => {
  8. console.log(jsonData);
  9. });
  10. /**
  11. * Output: HTML Data
  12. */
  13. const text = fetch("https://deno.land/");
  14. text.then((response) => {
  15. return response.text();
  16. }).then((textData) => {
  17. console.log(textData);
  18. });
  19. /**
  20. * Output: Error Message
  21. */
  22. const error = fetch("https://does.not.exist/");
  23. error.catch((error) => console.log(error.message));