From 765235341b6075bcf64d8ebcdb61e350d251514d Mon Sep 17 00:00:00 2001 From: Rob Waller Date: Wed, 26 Aug 2020 17:45:03 +0100 Subject: docs: add fetch and read/write examples (#7186) --- docs/examples/fetch_data.md | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 docs/examples/fetch_data.md (limited to 'docs/examples/fetch_data.md') diff --git a/docs/examples/fetch_data.md b/docs/examples/fetch_data.md new file mode 100644 index 000000000..ad47e90b1 --- /dev/null +++ b/docs/examples/fetch_data.md @@ -0,0 +1,46 @@ +# Fetch Data + +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](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). + +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. + +**Command:** `deno run --allow-net fetch.ts` + +```js +/** + * Output: JSON Data + */ +const json = fetch("https://api.github.com/users/denoland"); + +json.then((response) => { + return response.json(); +}).then((jsonData) => { + console.log(jsonData); +}); + +/** + * Output: HTML Data + */ +const text = fetch("https://deno.land/"); + +text.then((response) => { + return response.text(); +}).then((textData) => { + console.log(textData); +}); + +/** + * Output: Error Message + */ +const error = fetch("https://does.not.exist/"); + +error.catch((error) => console.log(error.message)); +``` -- cgit v1.2.3