fetch with get request code example
Example 1: js fetch 'post' json
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST',
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);
});
Example 2: javascript fetch api
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
Example 3: how to create a fetch function
const url = 'http://api.open-notify.org/astros.json'
const fetchurl = (url:string):void=>{
fetch(url).then(res=>res.json()).then(jsonRes=>{
console.log(jsonRes)
})
}
fetchurl(url)
Example 4: fetch api in javascript
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log('Request Failed', err));
Example 5: .fetch method
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Example 6: fetch api
const url = "http://dummy.restapiexample.com/api/v1/employee/40";
fetch(url)
.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}') );