JavaScript - GET request with fetch method
In this article, we would like to show you how to make GET requests with JavaScript Fetch API.
We will present 3 examples of GET request with the fetch method:
- basic promises based example,
- async-await - promises mixed based example with basic error protection
- async-await based example with basic error protection
The choice of method depends on the situation in which we want to use it, but the last approach is the most recommended in most cases.
This approach is fine, but with complex code, it gets a lot of callback and the code becomes quite unreadable.
Note:
You need to add a status check here as it is done in the following examples
xxxxxxxxxx
<html>
<body>
<script>
fetch('/examples/echo?text=hello')
.then((response) => response.text())
.then((text) => console.log(text))
.catch((error) => console.error(error));
</script>
</body>
</html>
In the presented approach, we used promises with async-await, so that you do not have to wrap the fetch function with the asynchronous method.
xxxxxxxxxx
<html>
<body>
<script>
fetch('/examples/echo?text=hello')
.then(async (response) => {
if (response.status == 200) {
const text = await response.text();
console.log(`Received data: ${text}`);
} else {
console.log(`Received error: status=${response.status}`);
}
})
.catch((error) => {
console.error(`Occured exception: ${error}`);
});
</script>
</body>
</html>
The last example is based on async-await - the advantage of this approach is readability and more convenient handling (most recommended).
xxxxxxxxxx
<html>
<body>
<script>
const doGet = async () => {
try {
const response = await fetch('/examples/echo?text=hello');
if (response.status == 200) {
const text = await response.text();
console.log(`Received data: ${text}`);
} else {
console.log(
`Received error: status=${response.status}`
);
}
} catch (error) {
console.error(`Occured exception: ${error}`);
}
};
doGet();
</script>
</body>
</html>