1fetch('https://example.com/profile', {
2 method: 'POST', // or 'PUT'
3 headers: {
4 'Content-Type': 'application/json',
5 },
6 body: JSON.stringify(data),
7})
8.then(response => response.json())
9.then(data => {
10 console.log('Success:', data);
11})
12.catch((error) => {
13 console.error('Error:', error);
14});
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
1// There were no quick access to mode and credentials to other fetch answers.
2// Data you'll be sending
3const data = { funny: "Absolutely not", educational: "yas" }
4
5fetch('https://example.com/api/', {
6 method: 'POST', // The method
7 mode: 'no-cors', // It can be no-cors, cors, same-origin
8 credentials: 'same-origin', // It can be include, same-origin, omit
9 headers: {
10 'Content-Type': 'application/json', // Your headers
11 },
12 body: JSON.stringify(data),
13}).then(returnedData => {
14 // Do whatever with returnedData
15}).catch(err => {
16 // In case it errors.
17})
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((myJson) => {
6 console.log(myJson);
7 });
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((data) => {
6 console.log(data);
7 });
8
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));