
Express-Async-Errors Node JS Example
Express-Async-Errors installation and usage example in a node js project.
A comprehensive guide to the Javascript Fetch API with examples for all methods and error handling.
In this tutorial, I'm going to explain how the Fetch API works and how to send request using Async/Await and Promises. Also, How to handle errors.
Sound good? Let's get started.
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.
It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.
Here's what a simple Fetch request setup looks like:
Code Copied!
fetch('http://example.com/posts')
.then(response => response.json())
.then(data => console.log(data));
However, Fetch requests can also contain much more options like this:
Code Copied!
fetch("http://example.com/posts", {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: { slug: "hello-world" },
})
.then((response) => response.json())
.then((data) => console.log(data));
Don't worry. You don't need to use all of these options. However, they're good to know.
Method => Request method such as (e.g., POST, PUT, DELETE).
Note that a request using the GET we don't provide this option.
Mode => This is used to determine if cross-origin requests lead to valid responses, and which properties of the response are readable.
Cache => Controls how the request will interact with the browser's HTTP cache.
Credentials => Indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests.
Headers => Contains the Headers object associated with the request.
For example: If you want to send a POST request with data of type JSON you need to provide the header "Content-Type": "application/json" to tell the server how to parse the data.
Body => Contains a ReadableStream with the body contents that have been added to the request.
Note that a request using the GET or HEAD method cannot have a body and null is return in these cases.
Now that we understand what's the content of a Fetch request. Let's take a look at the response.
Fetch response() object contains properties and methods.
Properties hold information about the sent request.
I will not go through all the properties but the important ones. If you want more in-depth information please see Response - Web APIs | MDN.
Response.body => A ReadableStream of the body contents.
Response.headers =>The Headers object associated with the response.
Response.ok => A boolean indicating whether the response was successful (status in the range 200–299) or not.
Response.status => The status code of the response.
Response.statusText => The status message corresponding to the status code. (e.g., OK for 200).
Methods are used to parse the response data to your desired data type.
For example: if a server sent response data in JSON like this:
Code Copied!
[
{
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto",
},
{
userId: 1,
id: 2,
title: "qui est esse",
body: "est rerum tempore vitae sequi sint nihil reprehenderit dolor beatae ea dolores neque fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis qui aperiam non debitis possimus qui neque nisi nulla",
},
{
userId: 1,
id: 3,
title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
body: "et iusto sed quo iure voluptatem occaecati omnis eligendi aut ad voluptatem doloribus vel accusantium quis pariatur molestiae porro eius odio et labore et velit aut",
}
]
You can't read the properties of this JSON object because it's stringified (Converted to string).
So, we need to use the response() object methods to convert it to an actual JSON object that we can use in our Javascript code.
I will not go through all the methods but the important ones. If you want more in-depth information please see Response - Web APIs | MDN.
Response.arrayBuffer() => Returns a promise that resolves with an ArrayBuffer representation of the response body.
Response.blob() => Returns a promise that resolves with a Blob representation of the response body.
Response.formData() => Returns a promise that resolves with a FormData representation of the response body.
Response.json() => Returns a promise that resolves with the result of parsing the response body text as JSON.
Response.text() => Returns a promise that resolves with a text representation of the response body.
Let's see how to send GET requests in Javascript using Fetch API.
This is a Fetch GET request example using Async / Await. Also, we're expecting a JSON response.
Code Copied!
async function get() {
const response = await fetch(
"http://example.com/posts"
);
const data = await response.json();
console.log(data);
}
Note that we used the method response.json() because we're expecting a JSON response.
This is a Fetch GET request example using Promises. Also, we're expecting a TEXT response.
Code Copied!
fetch('http://example.com/posts')
.then(response => response.text())
.then(data => console.log(data));
Note that we used the method response.text() because we're expecting a TEXT response.
Let's see how to send POST requests in Javascript using Fetch API.
This is a Fetch POST request example using Async / Await.
Code Copied!
async function post() {
const response = await fetch("https://example.com/posts", {
method: "POST",
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
});
const data = await response.json();
console.log(data);
}
This is a Fetch POST request example using Promises.
Code Copied!
fetch("https://example.com/posts", {
method: "POST",
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
Note that other methods (e.g., PUT, DELETE, PATCH) are similar to the POST method implementation.
Now that you know how to send requests and read responses. Let's take a look at handling errors since it's important to give feedback to the users if an error occurs.
Here's an example of handling Fetch API errors when working with Async / Await.
Code Copied!
async function get() {
const response = await fetch(
"https://example/posts"
);
//Check if response status is 200 - 299
if (!response.ok) {
const error = response.status;
//Here is where you give feedback to the user or log the error
throw new Error(error);
}
const data = await response.json();
console.log(data);
}
Here's an example of handling Fetch API errors when working with Promises.
Code Copied!
fetch("https://example/posts")
.then((response) => {
//Check if response status is 200 - 299
if (response.ok) {
return response.json();
}
const error = response.status;
throw new Error(error);
})
.then((data) => console.log(data))
.catch((error) => {
//Here is where you give feedback to the user or log the error
console.log(error);
});
In This tutorial