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

后端 未结 3 1608
难免孤独
难免孤独 2020-12-29 06: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

相关标签:
3条回答
  • 2020-12-29 06:43

    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;
        }    
    
    }
    
    0 讨论(0)
  • 2020-12-29 06:48

    Remember to separate async/await and then here is an example:

    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;
      }
    };
    
    0 讨论(0)
  • 2020-12-29 06:55

    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) {
            //
    }
    
    0 讨论(0)
提交回复
热议问题