A Fetch API provides a fetch method defined on a window object, which you can use to perform requests and sent it to the server. This method returns a Promise that you can use to retrieve the response of the request.
Copy fetch('https://api.mydomain.com').
then(response => response.json()).
then(data => this.setState({ data }));
Copy fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Copy fetch("/add", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
a: parseInt(a),
b: parseInt(b)
})
})
.then(res => res.json())
.then(data => {
const {
result
} = data;
document.querySelector(
".result"
).innerText = `The sum is: ${result}`;
})
.catch(err => console.log(err));
Copy // Some code
export async function getAllUsers() {
try{
const response = await fetch('/api/users');
return await response.json();
}catch(error) {
return [];
}
}
export async function createUser(data) {
const response = await fetch(`/api/user`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({user: data})
})
return await response.json();
}
Copy function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
Copy axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
const axios = require('axios');
export async function getAllUsers() {
try{
const response = await axios.get('/api/users');
console.log('response ', response)
return response.data;
}catch(error) {
return [];
}
}
export async function createUser(data) {
const response = await axios.post(`/api/user`, {user: data});
return response.data;
}