fetch()
is provided by Web API. We can use fetch()
to patch partial 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
let body = {
author: 'Tom',
}
try {
let res = await fetch(`http://localhost:3000/posts/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
let data = await res.json()
console.log(data)
} catch (e) {
console.error(e)
}
}
</script>
</html>
Line 12
let id = 2
let body = {
author: 'Tom',
}
- Prepare
id
andbody
separately to PATCH
Line 17
try {
let res = await fetch(`http://localhost:3000/posts/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
let data = await res.json()
console.log(data)
} catch (e) {
console.error(e)
}
id
:specifyid
directly on urlmethod
:specifyPATCH
for PATCH actionheaders
:assignapplication/json
toContent-Type
body
:usebody.stringify()
to transformbody
Object to String
Conclusion
- We have to assign
method
andheaders
for PATCH action underfetch()
- The body Object has to be
JSON.stringify()
to String before sending byfetch()