fetch()
is provided by Web API. We can use fetch()
to post new data to RESTful API without any packages.
Version
Alpine 3.10
POST
<!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 body = {
title: 'MongoDB',
author: 'Sam',
}
try {
let res = await fetch('http://localhost:3000/posts', {
method: 'POST',
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 body = {
title: 'MongoDB',
author: 'Sam',
}
- Prepare body Object to POST
Line 17
try {
let res = await fetch('http://localhost:3000/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
let data = await res.json()
console.log(data)
} catch (e) {
console.error(e)
}
method
:specifyPOST
for POST actionheaders
:assignapplication/json
toContent-Type
body
:usebody.stringify()
to transformbody
Object to String
Conclusion
- We have to assign
method
andheaders
for POST action underfetch()
- The body Object has to be
JSON.stringify()
to String before sending byfetch()