DEV Community

loading...
Cover image for The Fetch API - The ultimate hacker's tool

The Fetch API - The ultimate hacker's tool

leviathanprogramming profile image π‹π„π‘½πˆπ‘¨π“π‡π€π Programming ・2 min read

Many of you might use the fetch API and many of you might have not even heard of it. It is an extremely powerful tool that you can use to use and validate files, submit get, post, put, and delete requests, and do so much more.
Here are some examples of what you can do with the fetch API.

1. File Validator

To test if a user is inputting an existing/valid file that exists somewhere on the internet, you can use the fetch API to see if it works or not.

let fileName = "https://api.dictionaryapi.dev/api/v2/entries/en_US/dog";
fetch(fileName).then(() => {
    console.log("Valid File");
}).catch(err => {
    console.log("File does not exist.");
})
Enter fullscreen mode Exit fullscreen mode

Whether you plug in an HTML file, and Image URL, or a JSON file, you can see if it is a valid file. For example, if you wanted a user to put in a valid profile picture (URL), you can validate their image in less than ten lines of code.

2. JSON API fetching & using

This is one of the most common uses of the fetch API. You can get the API of a site and use it. For example, youtube has an API for each video like Length, Author, Likes, etc.
In this example, I will be fetching API from a dictionary.

let fileName = "https://api.dictionaryapi.dev/api/v2/entries/en_US/dog";
fetch(fileName)
.then(response => response.json())
.then(data => {
    console.log("The definition of the word 'dog' is "+data[0].meanings[1].definitions[0].definition)
}).catch(err => {
    console.log("File does not exist.");
})
Enter fullscreen mode Exit fullscreen mode

Now what I would do to view a JSON file is copy it, paste it into VSCode, and format it for better visibility.
Formatted JSON

3. Making AJAX requests

Making AJAX requests is also something really amazing you can do with the fetch API. Most sites have higher security levels but you can also make an ajax request from a different location if you have the right keys to do it.
Here's an example of making a basic ajax request.

document.querySelector("#ajax-form").addEventListener("submit", function(e){
    e.preventDefault()
    const form = new FormData(document.querySelector('#ajax-form'));
    fetch('/ajax-endpoint', {
      method: 'POST',
      body: form
    }).then(() => {
      //do whatever is supposed to happen (e.g, displaying a new post, etc.)
    }).catch(err => {
      console.log(err);
    });
});
Enter fullscreen mode Exit fullscreen mode

That's pretty much all I have to say. If you like my posts, don't forget to follow me on dev and subscribe to me at my website

Thanks for reading.
Happy Coding!

Discussion (0)

Forem Open with the Forem app