-
Notifications
You must be signed in to change notification settings - Fork 3
JavaScript: Fetch API
Ambreen Khan edited this page Dec 31, 2018
·
7 revisions
Get Request:
- Fetch API is a replacement for XMLHttpRequest
- It is a web API that can be used to create requests.
- Once fetch is called, it will return promises.
- To handle promises returned by fetch(), we chain .then() methods
- The .json() method converts a returned promise to a JSON object.
fetch('https://api-url-goes-here.com/endpoint').then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
return jsonResponse;
});
Post Request:
Fetch POST call takes two arguments
- An endpoint of the API
- An object that contains information needed for the POST request
fetch('https://api-url-goes-here.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: '200'})
}).then(response => {
if(response.ok){
return response.json();
}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
return jsonResponse;
});
async/await Get Request:
const getData = async () => {
try {
const response = await fetch('https://api-url-goes-here.com/endpoint');
if(response.ok){
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch (error){
console.log(error);
}
}
async/await Post Request:
const getData = async () => {
try{
const response = await fetch('https://api-url-goes-here.com/endpoint', {
method: 'POST',
body: JSON.stringify({id: 200})
});
if (response.ok){
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request failed!');
} catch (error){
console.log(error);
}
}
Website: https://softwaretestingtrends.com/
Facebook: https://www.facebook.com/softwaretestingtrend/
Twitter: https://twitter.com/ambysan
LinkedIn: https://www.linkedin.com/in/ambysan/