【问题标题】:Javascript: Fetch DELETE and PUT requestsJavascript:获取 DELETE 和 PUT 请求
【发布时间】:2017-03-10 02:55:32
【问题描述】:

我已经脱离了 Fetch 的 GET 和 POST 方法。但我找不到任何好的 DELETE 和 PUT 示例。

所以,我问你。您能否举一个使用 fetch 的 DELETE 和 PUT 方法的好例子。并稍微解释一下。

【问题讨论】:

    标签: javascript reactjs fetch http-delete http-put


    【解决方案1】:

    一些例子:

    async function loadItems() {
            try {
                let response = await fetch(`https://url/${AppID}`);
                let result = await response.json();
                return result;
            } catch (err) {
            }
        }
    
        async function addItem(item) {
            try {
                let response = await fetch("https://url", {
                    method: "POST",
                    body: JSON.stringify({
                        AppId: appId,
                        Key: item,
                        Value: item,
                        someBoolean: false,
                    }),
                    headers: {
                        "Content-Type": "application/json",
                    },
                });
                let result = await response.json();
                return result;
            } catch (err) {
            }
        }
    
        async function removeItem(id) {
            try {
                let response = await fetch(`https://url/${id}`, {
                    method: "DELETE",
                });
            } catch (err) {
            }
        }
    
        async function updateItem(item) {
            try {
                let response = await fetch(`https://url/${item.id}`, {
                    method: "PUT",
                    body: JSON.stringify(todo),
                    headers: {
                        "Content-Type": "application/json",
                    },
                });
            } catch (err) {
            }
        }
    

    【讨论】:

    • 嗯...真的吗???这没有意义……为什么要在 url 中发送 ID,而在正文中发送其余数据?我从来没有见过这样的 PUT 命中...
    【解决方案2】:

    对于 put 方法,我们有:

    const putMethod = {
     method: 'PUT', // Method itself
     headers: {
      'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
     },
     body: JSON.stringify(someData) // We send data in JSON format
    }
    
    // make the HTTP put request using fetch api
    fetch(url, putMethod)
    .then(response => response.json())
    .then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
    .catch(err => console.log(err)) // Do something with the error
    

    someData 的示例,我们可以有一些输入字段或您需要的任何内容:

    const someData = {
     title: document.querySelector(TitleInput).value,
     body: document.querySelector(BodyInput).value
    }
    

    在我们的data base 中将有这个json 格式:

    {
     "posts": [
       "id": 1,
       "title": "Some Title", // what we typed in the title input field
       "body": "Some Body", // what we typed in the body input field
     ]
    }
    

    对于删除方法,我们有:

    const deleteMethod = {
     method: 'DELETE', // Method itself
     headers: {
      'Content-type': 'application/json; charset=UTF-8' // Indicates the content 
     },
     // No need to have body, because we don't send nothing to the server.
    }
    // Make the HTTP Delete call using fetch api
    fetch(url, deleteMethod) 
    .then(response => response.json())
    .then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it
    .catch(err => console.log(err)) // Do something with the error
    

    在url中我们需要输入删除的id:https://www.someapi/id

    【讨论】:

      【解决方案3】:

      以下是使用 Firebase 的 React、redux 和 ReduxThunk 的 Delete 和 Put 示例:

      更新(PUT):

      export const updateProduct = (id, title, description, imageUrl) => {
          await fetch(`https://FirebaseProjectName.firebaseio.com/products/${id}.json`, {
        method: "PATCH",
        header: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          title,
          description,
          imageUrl,
        }),
      });
      
      dispatch({
        type: "UPDATE_PRODUCT",
        pid: id,
        productData: {
          title,
          description,
          imageUrl,
        },
      });
      };
      };
      

      删除:

      export const deleteProduct = (ProductId) => {
        return async (dispatch) => {
      await fetch(
        `https://FirebaseProjectName.firebaseio.com/products/${ProductId}.json`,
        {
          method: "DELETE",
        }
      );
      dispatch({
        type: "DELETE_PRODUCT",
        pid: ProductId,
      });
        };
      };
      

      【讨论】:

        【解决方案4】:

        好的,这也是一个 fetch DELETE 示例:

        fetch('https://example.com/delete-item/' + id, {
          method: 'DELETE',
        })
        .then(res => res.text()) // or res.json()
        .then(res => console.log(res))
        

        【讨论】:

        • 请注意,不需要解析结果。解析 res 为 text 会返回一个空字符串,解析为 JSON 会报解析错误。
        • 需要解析promise,因为首先res是promise。
        【解决方案5】:

        只是简单的答案。 获取删除

        function deleteData(item, url) {
          return fetch(url + '/' + item, {
            method: 'delete'
          })
          .then(response => response.json());
        }
        

        【讨论】:

          【解决方案6】:

          这是一个获取POST 的示例。您可以对DELETE 执行相同的操作。

          function createNewProfile(profile) {
              const formData = new FormData();
              formData.append('first_name', profile.firstName);
              formData.append('last_name', profile.lastName);
              formData.append('email', profile.email);
          
              return fetch('http://example.com/api/v1/registration', {
                  method: 'POST',
                  body: formData
              }).then(response => response.json())
          }
          
          createNewProfile(profile)
             .then((json) => {
                 // handle success
              })
             .catch(error => error);
          

          【讨论】:

          • 所以 POST、PUT 和 DELETE 在语法上是相同的?
          • 不同之处在于您需要记录的id 才能删除或放置。它现在看起来像 return fetch('http://example.com/api/v1/registration/1', { method: 'PUT', body: formData })
          • 如果API不需要记录的ID,为什么我们需要它?
          • 'Needing an id' 特定于 API。 is 始终为 true 的一点是,对于 PUTDELETE,您正在分别更新或删除资源 at URI。因此,如果对/x 发出DELETE 请求,我希望/x 之后会被删除。
          【解决方案7】:

          这里是使用 fetch API 的 CRUD 操作的一个很好的例子:

          “关于如何使用 Fetch API 执行 HTTP 请求的实用 ES6 指南”,作者:Dler Ari https://link.medium.com/4ZvwCordCW

          这是我为 PATCH 或 PUT 尝试的示例代码

          function update(id, data){
            fetch(apiUrl + "/" + id, {
              method: 'PATCH',
              body: JSON.stringify({
               data
              })
            }).then((response) => {
              response.json().then((response) => {
                console.log(response);
              })
            }).catch(err => {
              console.error(err)
            })
          

          删除:

          function remove(id){
            fetch(apiUrl + "/" + id, {
              method: 'DELETE'
            }).then(() => {
               console.log('removed');
            }).catch(err => {
              console.error(err)
            });
          

          有关更多信息,请访问使用 Fetch - Web API | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API。

          【讨论】:

          • 请记住,我们正在尝试在这里编写参考质量的内容;您不应该对所有内容都添加“感谢”,绝对不是表情符号(除非问答实际上是关于处理它们,例如 Unicode 处理)。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-17
          • 2013-12-06
          • 2017-11-14
          • 2018-12-20
          • 1970-01-01
          • 2019-07-14
          • 1970-01-01
          相关资源
          最近更新 更多