Подтвердить что ты не робот

Javascript: выборка запросов DELETE и PUT

Я получил за пределами методов GET и POST с Fetch. Но я не смог найти хорошего примера DELETE and PUT.

Итак, я прошу вас об этом. Не могли бы вы привести хороший пример методов DELETE и PUT с fetch. И объясни это немного.

4b9b3361

Ответ 1

Вот пример получения 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);

Ответ 2

Хорошо, вот еще пример 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))

Ответ 3

Просто простой ответ. УДАЛИТЬ УДАЛИТЬ

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

Ответ 4

Вот хороший пример операции CRUD с использованием API выборки:

"Практическое руководство ES6 по выполнению HTTP-запросов с использованием Fetch API", автор 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" | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.

Ответ 5

Для метода 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

В URL-адресе нам нужно ввести идентификатор удаления: https://www.someapi/id