Search This Blog

2026/10/15

Javascript:Fetch

 


Using fetch to make api call.

Code:

const link = "https://jsonplaceholder.typicode.com/posts/1"


fetch(link).then((res)=>{
   return res.json()
}).then((data)=>{
   console.log(data)
})



Output:
{
  userId: 1,
  id: 1,
  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
  body: 'quia et suscipit\n' +
    'suscipit recusandae consequuntur expedita et cum\n' +
    'reprehenderit molestiae ut ut quas totam\n' +
    'nostrum rerum est autem sunt rem eveniet architecto'
}



Now lets explore how to make post request.

//post request

const linkPost = "https://jsonplaceholder.typicode.com/posts";


fetch(linkPost, {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        title: "JavaScript",
        body: "Learning fetch POST call",
        userId: 1
    })
}).then((res)=>{
   return res.json()
}).then((data)=>{
   console.log(data)
})

Output:
{
  title: 'JavaScript',
  body: 'Learning fetch POST call',
  userId: 1,
  id: 101
}

No comments:

Post a Comment