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('http://example.com/songs')
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error(err));
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
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
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
import React, { useEffect, useState } from "react";
function App() {
const [user, setUser] = useState([]);
const fetchData = () => {
return fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => setUser(data));
}
useEffect(() => {
fetchData();
},[])
return (
<main>
<h1>User List</h1>
<ul>
{user && user.length > 0 && user.map((userObj, index) => (
<li key={userObj.id}>{userObj.name}</li>
))}
</ul>
</main>
);
}
export default App;
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');
}