點燈坊

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

Preparing Body Object for fetch()

Sam Xiao's Avatar 2022-11-10

When using fetch() for REST POST, we can easily prepare Body Object by Web API.

Version

Brave 1.45.123

Body

body000

The body Object is shown.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HTML Lab</title>
  </head>
  <body>
    <input id="id" value="0" />
    <input id="name" value="Sam" />
    <button onclick="onClick()">Submit</button>
  </body>
  <script>
    let onClick = () => {
      let id = document.querySelector('#id').value
      let name = document.querySelector('#name').value

      let body = { id, name }
      console.log(body)
    }
  </script>
</html>

Line 9

<input id="id" value="0" />
<input id="name" value="Sam" />
<button onclick="onClick()">Submit</button>
  • We have to assign the default value to <input>

Line 14

let onClick = () => {
  let id = document.querySelector('#id').value
  let name = document.querySelector('#name').value

  let body = { id, name }
  console.log(body)
}
  • Get id and name values by querySelector()
  • Combine variables to body Object

Conclusion

  • Web API is not MVVM pattern. We have to get values by querySelector() manually