JavaScript fetch() Method
The fetch() method in JavaScript is used to request data from a server. The request can be of any type of API that returns the data in JSON or XML. The fetch() method requires one parameter, the URL to request, and returns a promise.
Syntax:
fetch('url') //api for the get request .then(response => response.json()) .then(data => console.log(data));
Parameters: This method requires one parameter and accepts two parameters:
- URL: It is 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.
Example 1: This example shows the use of the javascript fetch() method.
NOTE: Without options, Fetch will always act as a get request.
Javascript
<script> // API for get requests let fetchRes = fetch( // fetchRes is the promise to resolve // it by using.then() method fetchRes.then(res => res.json()).then(d => { console.log(d) }) </script> |
Output:
Making Post Request using Fetch: Post requests can be made using fetch by giving options as given below:
let options = { method: 'POST', headers: { 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(data) }
Example 2: In this example, we will see the use of the post method in fetch() in javascript.
Javascript
<script> user = { "name" : "Geeks for Geeks" , "age" : "23" } // Options to be given as parameter // in fetch for making requests // other then GET let options = { method: 'POST' , headers: { 'Content-Type' : 'application/json;charset=utf-8' }, body: JSON.stringify(user) } // Fake api for making post requests let fetchRes = fetch( options); fetchRes.then(res => res.json()).then(d => { console.log(d) }) </script> |
Output:
Please Login to comment...