xxxxxxxxxx
fetch('https://apiYouWantToFetch.com/players') // returns a promise
.then(response => response.json()) // converting promise to JSON
.then(players => console.log(players)) // console.log to view the response
xxxxxxxxxx
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
xxxxxxxxxx
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
xxxxxxxxxx
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
xxxxxxxxxx
fetch('/payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'url': '/payment',
"X-CSRF-Token": document.querySelector('input[name=_token]').value
},
})
xxxxxxxxxx
// fetch API
var myData = async () => {
try {
const raw_response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!raw_response.ok) { // check for the 404 errors
throw new Error(raw_response.status);
}
const json_data = await raw_response.json();
console.log(json_data);
}
catch (error) { // catch block for network errors
console.log(error);
}
}
fetchUsers();
xxxxxxxxxx
async function postData() {
// Define the URL of the resource you want to access
const url = "https://example.com/api/endpoint";
// Define the data you want to send in the request
const data = {
name: "John Doe",
email: "johndoe@example.com"
};
// Use the `fetch` function to make a POST request to the URL
const response = await fetch(url, {
method: "POST", // specify that you want to make a POST request
body: JSON.stringify(data), // convert the data object to a JSON string
headers: {
"Content-Type": "application/json" // set the content type of the request
}
});
// Check the status code of the response to make sure it was successful
if (response.ok) {
// If the request was successful, get the data from the response
const result = await response.json();
// Do something with the data here
console.log(result);
} else {
// If the request was not successful, handle the error here
console.error("Error:", response.statusText);
}
}
xxxxxxxxxx
// Error handling while fetching API
const url = "http://dummy.restapiexample.com/api/v1/employee/40";
fetch(url) //404 error
.then( res => {
if (res.ok) {
return res.json( );
} else {
return Promise.reject(res.status);
}
})
.then(res => console.log(res))
.catch(err => console.log('Error with message: ${err}') );
xxxxxxxxxx
async function getData() {
const url = "https://example.org/products.json";
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const json = await response.json();
console.log(json);
} catch (error) {
console.error(error.message);
}
}
xxxxxxxxxx
try {
const response = await fetch('https://restcountries.com/v4.1/all');
if (response.ok) {
console.log('Promise resolved and HTTP status is successful');
// ...do something with the response
} else {
console.error('Promise resolved but HTTP status failed');
}
} catch {
console.error('Promise rejected');
}