Fetch: Q: How would I make a DELETE request?

Created on 2 Jun 2015  路  5Comments  路  Source: github/fetch

I tried something like this:

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

and I get Uncaught TypeError: Cannot read property 'then' of undefined

Most helpful comment

A bit late to this but you could improve on it like

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

response.json() already returns a promise with json, so the last .then is unnecessary.

All 5 comments

That call looks right to me. And I assume you already figured out the problem, but the 'Uncaught TypeError' might be happening because the server is returning a response that Fetch doesn't handle.

@theopak yeah, what I was doing wrong - forgot to return the promise. So should look like:

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

A bit late to this but you could improve on it like

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

response.json() already returns a promise with json, so the last .then is unnecessary.

another one!

fetch-delete.js

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2019-03-26
 *
 * @description fetchDelete
 * @augments
 * @example
 *
 */

const fetchDelete = (url= ``, id="") => {
    let trueUrl = `${url}/${item}`;
    return fetch(trueUrl, {
        method: 'delete'
    })
    .then(res => res.json());
};


export default fetchDelete;

export {
    fetchDelete,
};

demo

import {fetchDelete} from "./fetch-delete";

let url = `/api/v4/deleteUserById`;
let id = `123456789`;

fetchDelete(url, id)
.then(data => console.log(`do something with your data`, JSON.stringify(data, null, 4)));


Do anyone know how to use fetch Delete post API in angular

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mmocny picture mmocny  路  3Comments

kocur4d picture kocur4d  路  3Comments

seekcx picture seekcx  路  4Comments

hannesvdvreken picture hannesvdvreken  路  4Comments

huanghaiyang picture huanghaiyang  路  3Comments