fetching in javascript code example
Example 1: Add no cores to fetch
const data = { funny: "Absolutely not", educational: "yas" }
fetch('https://example.com/api/', {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then(returnedData => {
}).catch(err => {
})
Example 2: javascript fetch api post
fetch('https://example.com/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
'foo': 'bar'
}),
})
.then((res) => res.json())
.then((data) => {
})
.catch((err) => console.log(err));
Example 3: fetch api in js
var myData = async () => {
try {
const raw_response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!raw_response.ok) {
throw new Error(raw_response.status);
}
const json_data = await raw_response.json();
console.log(json_data);
}
catch (error) {
console.log(error);
}
}
fetchUsers();
Example 4: fetch javascript
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);
});