【问题标题】:Proper Way to Make API Fetch 'POST' with Async/Await使用 Async/Await 使 API 获取“POST”的正确方法
【发布时间】:2018-10-07 09:08:17
【问题描述】:

我正在处理一个需要我向 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;
};

【问题讨论】:

  • awaitfetch API 的工作方式没有影响。您可以像使用 fetch 的任何其他方式一样将其作为发布请求。

标签: javascript reactjs post async-await fetch


【解决方案1】:

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

要发帖,只需在 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;
    }    

}

【讨论】:

  • 您也可以使用await 来读取响应流:const data = fetch(url); const json = await data.json();
  • 在我的情况下,浏览器在 POST 调用之前强制进行飞行前 OPTIONS 调用。我想要这样的东西来等待 OPTIONS 和 POST 调用完成并从 POST 调用返回数据。感谢分享。
  • @StangSpree 预检呼叫正在自动完成。也许您的后端不支持调用,这可能是浏览器抱怨的原因
【解决方案2】:

这是一个配置示例:

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

【讨论】:

    【解决方案3】:

    2021 年回答:以防万一您在这里寻找如何使用 async/await 或 Promise 发出 GET 和 POST Fetch api 请求(与 axios 相比)。

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

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

    使用 Promises 的 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 获取请求:

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

    【讨论】:

      【解决方案4】:

      请记住将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;
        }
      };
      

      【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2019-04-21
      • 1970-01-01
      • 2014-03-16
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      相关资源
      最近更新 更多