module for fetch api javascript code example
Example 1: fetch
// This will fetch api.example.com/comments with a header and a body
fetch(`https://api.example.com/comments`, {
method: 'POST', //This could be any http method
headers: {
'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
'Content-Type': 'application/json',
},
body: JSON.stringify({
UID: 58,
Comment: "Fetch is really easy!",
}),
})
.then((response) => response.json())
.then((newComment) => {
// Do something magical with your newly posted comment :)
});
Example 2: fetch api in javascript
// GET Request.
fetch('https://jsonplaceholder.typicode.com/users')
// Handle success
.then(response => response.json()) // convert to json
.then(json => console.log(json)) //print data to console
.catch(err => console.log('Request Failed', err)); // Catch errors