The Fetch API is a promise-based API of JavaScript for making asynchronous HTTP requests in the browser similar to XMLHttpRequest (XHR).
the fetch API is a simple and clean API that uses promises to provides more powerful features to fetch resources from the server. Fetch API is standardized now and is supported by all modern browsers except IE. The fetch() method only has one mandatory argument: the URL of the resource that we want to fetch.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
// handle response data
})
.catch(err => {
// handle errors
});
// GET Request:-
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => {
console.log(data) // Prints result from `response.json()` in getRequest
})
.catch(error => console.error(error))
// POST Request:-
let data = {
first_name: 'John',
last_name: 'Adams',
job_title: 'Software Engineer'
};
const options = {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}
fetch('https://jsonplaceholder.typicode.com/users', options)
.then(res => res.json())
.then(res => console.log(res));
Comments
Post a Comment