使用Async / Await进行API提取'POST'的正确方法

时间:2018-04-26 15:28:27

标签: javascript reactjs post fetch

我正在开展一个项目,要求我向API发出请求。使用Async / Await发出POST请求的正确形式是什么?

例如,这是我的获取以获取所有设备的列表。我如何将此请求更改为POST以创建新设备?我知道我必须添加一个带有数据主体的标题。

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

4 个答案:

答案 0 :(得分:6)

以下是配置示例:

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

答案 1 :(得分:5)

实际上你的代码可以这样改进:

做一个帖子只需在fetch call的设置上添加方法。

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

    const data = await fetch(`http://${location}:9000/api/sensors/`, settings)
        .then(response => response.json())
        .then(json => {
            return json;
        })
        .catch(e => {
            return e
        });

    return data;


}

答案 2 :(得分:2)

2021 答案:以防万一您登陆这里寻找与 axios 相比如何使用 async/await 或 promise 发出 GET 和 POST Fetch api 请求。

我使用 jsonplaceholder fake API 来演示:

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

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

使用 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)
  })

使用 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)
  })  

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

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

答案 3 :(得分:0)

请记住避免合并async/awaitthen,这是一个示例:

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