The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that returns the data of the format JSON or XML. This method returns a promise.
Syntax:
fetch( url, options )
Parameters: This method accept two parameters as mentioned above and described below:
- 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 promises whether it is resolved or not. The return data can be of the format JSON or XML.
It can be the array of objects or simply a single object.
Example 1:
NOTE: Without options Fetch will always act as a get request.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >JavaScript | fetch() Method</ title > </ head > < body > < 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 > </ body > </ html > |
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
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >JavaScript | fetch() Method</ title > </ head > < body > < 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 > </ body > </ html > |
Output: