xxxxxxxxxx
fetch("https://catfact.ninja/fact")
.then((res) => res.json())
.then((data) => {
console.log(data);
});
xxxxxxxxxx
fetch('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
xxxxxxxxxx
const fetchData = async () => {
try {
const response = await fetch('http://example.com/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-My-Custom-Header': '123', //optional
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
// ...
}),
});
const json = await response.json();
} catch (error) {
console.error(error);
}
}
xxxxxxxxxx
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
xxxxxxxxxx
fetch('https://example.com/path',
{method:'GET',
headers: {
'Authorization': 'Basic ' + btoa('login:password') //use btoa in js and Base64.encode in node
}
})
.then(response => response.json())
.then(json => console.log(json));
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
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
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');
}
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);
}
}