點燈坊

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

Using fetch() to GET Data from RESTful API

Sam Xiao's Avatar 2022-12-30

fetch() is provided by Web API. We can use fetch() to get data from RESTful API without any packages.

Version

Alpine 3.10

GET

<!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)">
    <ul>
      <template x-for="x in posts">
        <li x-text="x.title" />
      </template>
    </ul>
  </body>
  <script>
    let init = async x => {
      try {
        let res = await fetch('http://localhost:3000/posts')
        let data = await res.json()
        x.posts = data
      } catch (e) {
        console.error(e)
      }
    }
  </script>
</html>

Line 17

let init = async x => {
  try {
    let res = await fetch('http://localhost:3000/posts')
    let data = await res.json()
    x.posts = data
  } catch (e) {
    console.error(e)
  }
}
  • fetch():use fetch() to get Response from GET action
  • json():use json() to transform from Response to JSON

Conclusion

  • Since fetch() returns Promise, we have to use async await to deal with the data returned by fetch()