點燈坊

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

Using fetch() to POST New Data to RESTful API

Sam Xiao's Avatar 2022-12-30

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:specify POST for POST action
  • headers:assign application/json to Content-Type
  • body:use body.stringify() to transform body Object to String

Conclusion

  • We have to assign method and headers for POST action under fetch()
  • The body Object has to be JSON.stringify() to String before sending by fetch()