1//Obj of data to send in future like a dummyDb
2const data = { username: 'example' };
3
4//POST request with body equal on data in JSON format
5fetch('https://example.com/profile', {
6 method: 'POST',
7 headers: {
8 'Content-Type': 'application/json',
9 },
10 body: JSON.stringify(data),
11})
12.then((response) => response.json())
13//Then with the data from the response in JSON...
14.then((data) => {
15 console.log('Success:', data);
16})
17//Then with the error genereted...
18.catch((error) => {
19 console.error('Error:', error);
20});
21
22// Yeah
1fetch('https://example.com/profile', {
2 method: 'POST',
3 headers: { 'Content-Type': 'application/json' },
4 body: JSON.stringify({
5 'foo': 'bar'
6 }),
7})
8 .then((res) => res.json())
9 .then((data) => {
10 // Do some stuff ...
11 })
12 .catch((err) => console.log(err));
1method:"POST",
2body:JSON.stringify(data),
3 headers:{
4 "content-type": "application/json"
5 }
1var myHeaders = new Headers();
2
3var myInit = { method: 'POST',
4 headers: myHeaders,
5 mode: 'cors',
6 cache: 'default' };
7
8fetch('flowers.jpg',myInit)
9.then(function(response) {
10 return response.blob();
11})
12.then(function(myBlob) {
13 var objectURL = URL.createObjectURL(myBlob);
14 myImage.src = objectURL;
15});
16
17
1// Example POST method implementation:
2async function postData(url = '', data = {}) {
3 // Default options are marked with *
4 const response = await fetch(url, {
5 method: 'POST', // *GET, POST, PUT, DELETE, etc.
6 mode: 'cors', // no-cors, *cors, same-origin
7 cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
8 credentials: 'same-origin', // include, *same-origin, omit
9 headers: {
10 'Content-Type': 'application/json'
11 // 'Content-Type': 'application/x-www-form-urlencoded',
12 },
13 redirect: 'follow', // manual, *follow, error
14 referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
15 body: JSON.stringify(data) // body data type must match "Content-Type" header
16 });
17 return response.json(); // parses JSON response into native JavaScript objects
18}
19
20postData('https://example.com/answer', { answer: 42 })
21 .then(data => {
22 console.log(data); // JSON data parsed by `data.json()` call
23 });
24
1var formData = new FormData();
2var fileField = document.querySelector("input[type='file']");
3
4formData.append('username', 'abc123');
5formData.append('avatar', fileField.files[0]);
6
7fetch('https://example.com/profile/avatar', {
8 method: 'PUT',
9 body: formData
10})
11.then(response => response.json())
12.catch(error => console.error('Error:', error))
13.then(response => console.log('Success:', response));