Proper Way to Make API Fetch 'POST' with Async/Await

70,555

Solution 1

actually your code can be improved like this:

to do a post just add the method on the settings of the fetch call.

getDevices = async () => {
    const location = window.location.hostname;
    const settings = {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }
    };
    try {
        const fetchResponse = await fetch(`http://${location}:9000/api/sensors/`, settings);
        const data = await fetchResponse.json();
        return data;
    } catch (e) {
        return e;
    }    

}

Solution 2

Here is an example with configuration:

try {
    const config = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    }
    const response = await fetch(url, config)
    //const json = await response.json()
    if (response.ok) {
        //return json
        return response
    } else {
        //
    }
} catch (error) {
        //
}

Solution 3

2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.

I'm using jsonplaceholder fake API to demonstrate:

Fetch api GET request using async/await:

         const asyncGetCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts');
                 const data = await response.json();
                // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
            // enter your logic for when there is an error (ex. error toast)
                  console.log(error)
                 } 
            }


          asyncGetCall()

Fetch api POST request using async/await:

    const asyncPostCall = async () => {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
                 method: 'POST',
                 headers: {
                   'Content-Type': 'application/json'
                   },
                   body: JSON.stringify({
             // your expected POST request payload goes here
                     title: "My post title",
                     body: "My post content."
                    })
                 });
                 const data = await response.json();
              // enter you logic when the fetch is successful
                 console.log(data);
               } catch(error) {
             // enter your logic for when there is an error (ex. error toast)

                  console.log(error)
                 } 
            }

asyncPostCall()

GET request using Promises:

  fetch('https://jsonplaceholder.typicode.com/posts')
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
    // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })

POST request using Promises:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
   body: JSON.stringify({
     // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
})
  .then(res => res.json())
  .then(data => {
   // enter you logic when the fetch is successful
    console.log(data)
  })
  .catch(error => {
  // enter your logic for when there is an error (ex. error toast)
   console.log(error)
  })  

GET request using Axios:

        const axiosGetCall = async () => {
            try {
              const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
    // enter you logic when the fetch is successful
              console.log(`data: `, data)
           
            } catch (error) {
    // enter your logic for when there is an error (ex. error toast)
              console.log(`error: `, error)
            }
          }
    
    axiosGetCall()

POST request using Axios:

const axiosPostCall = async () => {
    try {
      const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts',  {
      // your expected POST request payload goes here
      title: "My post title",
      body: "My post content."
      })
   // enter you logic when the fetch is successful
      console.log(`data: `, data)
   
    } catch (error) {
  // enter your logic for when there is an error (ex. error toast)
      console.log(`error: `, error)
    }
  }


axiosPostCall()

Solution 4

Remember to separate async/await and then here is an example:

const addDevice = async (device) => {
  const { hostname: location } = window.location;
  const settings = {
    method: 'POST',
    body: JSON.stringify(device),
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
  }

  const response = await fetch(`http://${location}:9000/api/sensors/`, settings);
  if (!response.ok) throw Error(response.message);

  try {
    const data = await response.json();
    return data;
  } catch (err) {
    throw err;
  }
};
Share:
70,555
Nik Ackermann
Author by

Nik Ackermann

Updated on December 19, 2021

Comments

  • Nik Ackermann
    Nik Ackermann over 2 years

    I'm working on a project that requires me to make requests to an API. What is the proper form for making a POST request with Async/Await?

    As an example, here is my fetch to get a list of all devices. How would I go about changing this request to POST to create a new device? I understand I would have to add a header with a data body.

    getDevices = async () => {
      const location = window.location.hostname;
      const response = await fetch(
        `http://${location}:9000/api/sensors/`
      );
      const data = await response.json();
      if (response.status !== 200) throw Error(data.message);
      return data;
    };