Warm tip: This article is reproduced from stackoverflow.com, please click
fetch javascript post reactjs

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

发布于 2020-03-27 10:16:00

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;
};
Questioner
Nik Ackermann
Viewed
222
Prince Hernandez 2019-08-11 07:12

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;
    }    

}