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//
1fetch('http://example.com/movies.json')
2 .then((response) => {
3 return response.json();
4 })
5 .then((myJson) => {
6 console.log(myJson);
7 });
1fetch('https://jsonplaceholder.typicode.com/todos/1')
2 .then(response => response.json())
3 .then(json => console.log(json))
1// This will fetch api.example.com/comments with a header and a body
2fetch(`https://api.example.com/comments`, {
3 method: 'POST', //This could be any http method
4 headers: {
5 'Authorization': 'Basic SGVsbG8gdGhlcmUgOikgSGF2ZSBhIGdvb2QgZGF5IQ==',
6 'Content-Type': 'application/json',
7 },
8 body: JSON.stringify({
9 UID: 58,
10 Comment: "Fetch is really easy!",
11 }),
12})
13.then((response) => response.json())
14.then((newComment) => {
15 // Do something magical with your newly posted comment :)
16});
1const fetch = require('node-fetch');
2
3 let response = await fetch(`your url paste here`, {
4 headers: {
5 Authorization: `Token ${API_TOKEN}`,
6 "Content-Type": "application/json",
7 },
8 body: JSON.stringify(payload),
9 method: 'POST',
10 });
11 const results = await response.json();
12 console.log("======> :: results", results);
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));
1fetch('path-to-the-resource-to-be-fetched')
2 .then((response) => {
3
4 // Code for handling the response
5 })
6 .catch((error) => {
7
8 // Code for handling the error
9 });