This content originally appeared on DEV Community and was authored by
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.");
})
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.");
})
Now what I would do to view a JSON file is copy it, paste it into VSCode, and format it for better visibility.
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);
});
});
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!
This content originally appeared on DEV Community and was authored by
| Sciencx (2021-04-26T13:29:08+00:00) The Fetch API – The ultimate hacker’s tool. Retrieved from https://www.scien.cx/2021/04/26/the-fetch-api-the-ultimate-hackers-tool/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.