简体   繁体   English

使用 Async/Await 使 API 获取“POST”的正确方法

[英]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.我正在处理一个需要我向 API 发出请求的项目。 What is the proper form for making a POST request with Async/Await?使用 Async/Await 发出 POST 请求的正确形式是什么?

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?我将如何将此请求更改为 POST 以创建新设备? 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;
};

actually your code can be improved like this:实际上你的代码可以这样改进:

to do a post just add the method on the settings of the fetch call.做一个帖子只需在 fetch 调用的设置上添加方法。

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

}

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) {
        //
}

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. 2021 答案:以防万一您登陆这里寻找与 axios 相比如何使用 async/await 或 promise 进行 GET 和 POST Fetch api 请求。

I'm using jsonplaceholder fake API to demonstrate:我正在使用 jsonplaceholder fake API 来演示:

Fetch api GET request using async/await:使用 async/await 获取 api GET 请求:

         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:使用 async/await 获取 api POST 请求:

    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:使用 Promise 的 GET 请求:

  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:使用 Promise 的 POST 请求:

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:使用 Axios 的 GET 请求:

        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:使用 Axios 的 POST 请求:

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()

Remember to separate async/await and then here is an example:请记住将async/await分开, then这里是一个示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM