React:获取DELETE和PUT请求

Kir*_*tas 23 javascript http-put fetch http-delete reactjs

我用Fetch得到了GET和POST方法之外的东西.但我找不到任何好的DELETE和PUT示例.

所以,我问你.你能举一个带有fetch的DELETE和PUT方法的好例子吗?并解释一下.

Fla*_*der 29

这是一个获取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);
Run Code Online (Sandbox Code Playgroud)

  • 不同之处在于您需要记录的`id`来DELETE或PUT.它现在看起来像`return fetch('http://example.com/api/v1/registration/1', {``method:'PUT',``body:formData``})` (6认同)
  • “需要 ID”特定于 API。始终为 true 的一点是,使用“PUT”和“DELETE”分别更新或删除 URI 处的资源。因此,如果对“/x”执行“DELETE”请求,我希望“/x”之后被删除。 (3认同)

Gre*_*dev 23

对于 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
Run Code Online (Sandbox Code Playgroud)

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

const someData = {
 title: document.querySelector(TitleInput).value,
 body: document.querySelector(BodyInput).value
}
Run Code Online (Sandbox Code Playgroud)

在我们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
 ]
}
Run Code Online (Sandbox Code Playgroud)

对于删除方法,我们有:

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
Run Code Online (Sandbox Code Playgroud)

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


Dam*_*ica 10

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

fetch('https://example.com/delete-item/', {
  method: 'DELETE',
  headers: {'content-type': 'application/json'},
  body: JSON.stringify({id: '5bdcdfa40f0a326f858feae0'})
})
.then(res => res.text()) // OR res.json()
.then(res => console.log(res))
Run Code Online (Sandbox Code Playgroud)

  • 请注意,无需解析结果。将 res 解析为文本将返回空字符串,将其解析为 JSON 将给出解析错误。 (2认同)

Mr *_*Fun 7

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

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


小智 6

一些例子:

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) {
        }
    }
Run Code Online (Sandbox Code Playgroud)


Mur*_*ain 5

下面是使用 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)
  })
Run Code Online (Sandbox Code Playgroud)

对于删除:

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

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