Menu

1 / 2

JS fetch()

DEV Community·Nanthini Ammu·6 months ago
#lvMD052A
#api#beginners#javascript#webdev#response
Reading 0:00
15s threshold

What is fetch():

fetch() is a built-in function used to make network/HTTP requests.

It returns a Promise.

The fetch() function returns a Promise which is fulfilled with a Response object representing the server's response.

You can then check the request status and extract the body of the response in various formats, including text and JSON.

HTTP Methods :

GET - get data

POST - create data

PUT - update data

DELETE - delete data

Syntax : fetch(url, options)

url → API endpoint

options → method, headers, body, etc.

fetch(url) - Sends request,Returns a Promise.

.then(response => ...) response contains, status (200, 404…),headers,body -not readable yet.

response.json() - Converts body into JavaScript object,also returns a Promise.

.then(data => console.log(data)) - get data.

Basic get request :

fetch ( " https://jsonplaceholder.typicode.com/posts " ) . then (( response ) => response . json ()) . then (( data ) => console . log ( data )) . catch (( err ) => console .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.