Fetch API

 


 Fetch API in jsThe fetch() method in JavaScript is used to request data from a server.

The request can be of any API that returns the data in JSON or XML.

This method required 

 1. one parameter

 2. The URL to request

 3. returns a promise.

 

 Syntex: 

    fetch("URL")

    .then(response =>{ 

   response.json()}).then((data)=>{

   console.log(data)

   });

url= ' https://api.github.com/user'
    fetch(url).then((response)=>{
        return response.json();
    }).then((data)=>{
        console.log(data)
    })


Parameters: This method requires one parameter and accepts two parameters:

  • URL: The URL to which the request is to be made.
  • Options: It is an array of properties. It is an optional parameter.

Return Value: It returns a promise whether it is resolved or not. 

##The return data can be of the format JSON or XML. 

###It can be an array of objects or simply a single object.

----NOTE: Without options, Fetch will always act as a get request.---


Making Post Request using Fetch: Post requests can be made using fetch 

Here write 

1. firstly write a function: function postData()

2. second write parameter- a. URL

                                           b. data 
                                           c. params{

                                             }-- method, header, body;

     function write-- fetch(url, params).then((response)=>{

                                return response.json();

                               }).then ((data)=>{

                               console.log(data)

                               });

function postData(){
    url= ' https://dummyjson.com/products/1'
    data= ''
    params= {
        method: 'post',
        header:
        {'content-Type': 'aplication/jeson'
    },
     body: data
    }
    fetch(url, params).then((response)=>{
        return response.json();
    }).then((data)=>{
        console.log(data)
    })
}

Comments