React:获取DELETE和PUT请求

时间:2016-10-27 12:14:52

标签: javascript reactjs fetch

我已经使用Fetch获得了GET和POST方法。但我找不到任何好的DELETE和PUT示例。

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

7 个答案:

答案 0 :(得分:22)

这是一个fetch 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);

答案 1 :(得分:3)

获取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))

答案 2 :(得分:1)

一些例子:

异步函数loadItems(){ 尝试{ let response =等待fetch(https://url/${AppID}); 让结果=等待response.json(); 返回结果; } 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) {
    }
}

答案 3 :(得分:0)

简单回答。 获取删除

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

答案 4 :(得分:0)

以下是使用访存API进行CRUD操作的好例子:

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

这是我为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)
  });

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

答案 5 :(得分:0)

对于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
}

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

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

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

答案 6 :(得分:0)

以下是使用Firebase删除和放置React&redux和ReduxThunk的示例:

更新(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,
});
  };
};