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});
1// Fetch and Async/Await
2
3const url = 'http://dummy.restapiexample.com/api/v1/employees';
4const fetchUsers = async () => {
5 try {
6 const res = await fetch(url);
7 // check for 404 error
8 if (!res.ok) {
9 throw new Error(res.status);
10 }
11 const data = await res.json();
12 console.log(data);
13 }
14 // catch block for network errors
15 catch (error) {
16 console.log(error);
17 }
18}
19fetchUsers( );
1// Error handling while fetching API
2
3const url = "http://dummy.restapiexample.com/api/v1/employee/40";
4fetch(url) //404 error
5 .then( res => {
6 if (res.ok) {
7 return res.json( );
8 } else {
9 return Promise.reject(res.status);
10 }
11 })
12 .then(res => console.log(res))
13 .catch(err => console.log('Error with message: ${err}') );
1// Making get requests
2
3const url = "http://dummy.restapiexample.com/api/v1/employees";
4fetchurl()
5 .then(res => {
6 console.log(res);
7})
8 .catch(err => {
9 console.log('Error: ${err}' );
10});
1fetch('http://example.com/movies.json')
2 .then(response => response.json())
3 .then(data => console.log(data));
4
1// Making post request
2
3const url = 'http://dummy.restapiexample.com/api/v1/create'
4const user = {
5 name: 'Rahul'
6 age: '16'
7 salary: '000'
8};
9
10const options = {
11 method: 'POST'
12 body: JSON.stringify(user),
13}
14
15fetch(url, options)
16 .then( res => res.json())
17 .then( res=> console.log(res));