Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

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

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;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...