點燈坊

失くすものさえない今が強くなるチャンスよ

Using fetch() to DELETE Data to RESTful API

Sam Xiao's Avatar 2022-12-30

fetch() is provided by Web API. We can use fetch() to delete data to RESTful API without any packages.

Version

Alpine 3.10

PATCH

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://unpkg.com/alpinejs" defer></script>
    <title>Alpine Lab</title>
  </head>
  <body x-data="{ posts: [] }" x-init="init($data)"></body>
  <script>
    let init = async x => {
      let id = 2

      try {
        let res = await fetch(`http://localhost:3000/posts/${id}`, {
          method: 'DELETE',
        })
        let data = await res.json()
        console.log(data)
      } catch (e) {
        console.error(e)
      }
    }
  </script>
</html>

Line 12

let id = 2
  • Prepare id and body separately to DELETE

Line 14

try {
  let res = await fetch(`http://localhost:3000/posts/${id}`, {
    method: 'DELETE',
  })
  let data = await res.json()
  console.log(data)
} catch (e) {
  console.error(e)
}
  • id:specify id directly on url
  • method:specify DELETE for DELETE action

Conclusion

  • We have to assign method for DELETE action under fetch()