Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 18, 2021 11:44 pm GMT

Sending POST Request In JS Using fetch

What's POST request

POST: is a request that is used for sending information or data to a specific server.

POST request using then and catch

const postTodo = (todo) => {  fetch('https://jsonplaceholder.typicode.com/posts',{    method:'POST',    body:JSON.stringify(todo),    headers:{      'header-name':'header-value'    }  }).then(response => response.json())    .then(data => console.log(data) /* {id:101} */)    .catch(e => console.log('something went wrong :(', e))}const data = {  title: 'buy food',  body: "buy healthy food",  userId: 8,};postTodo();

POST request using async and await

const postTodo = async (todo) => {  try {  const response = await fetch('https://jsonplaceholder.typicode.com/posts',{    method:'POST',    headers:{      'header-name': 'header-value'    },    body:JSON.stringify(todo)  })  const data = await response.json();  console.log(data); // {id:101}  }catch(e){    console.log('something went wrong :(', e)  }}const data = {  title: 'buy food',  body: "buy healthy food",  userId: 8,};postTodo(data);

Suggested Posts

To Contact Me:

Happy codding!


Original Link: https://dev.to/ayabouchiha/sending-post-request-in-js-using-fetch-3lkd

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To