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
andbody
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
:specifyid
directly on urlmethod
:specifyDELETE
for DELETE action
Conclusion
- We have to assign
method
for DELETE action underfetch()