LoginSignup
1
0

More than 1 year has passed since last update.

Fetch APIとaxiosの違い

Last updated at Posted at 2022-06-09

HTTPメソッド

Fetch API

Fetch APIはmethod:"POST"等と記述する必要があります。

Fetch API
export default function Sample () {
  const onButtonClick = () => {
    const params = {
      method: "POST",
      body: JSON.stringify({name: "サンプル"})
    }
    fetch("/api/user", params)
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )

axios

axiosの場合には以下のようになります。

axios
import axios from "axios";

export default function Sample () {
  const onButtonClick = () => {
    axios.post("/api/user", {name: "サンプル"})
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )
}

JSONデータ

Fetch API

Fetch APIはresponseで受け取りJSONを抽出する必要があります。

Fetch API
export default function Sample () {
  const onButtonClick = () => {
    fetch("/api/user")
      .then((res) => res.json()) 
      .then((user) => alert(`ユーザー名:${user.name}`))  
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )
}

axios

axiosの場合には以下のようになります。

axios
import axios from "axios";

export default function Sample () {
  const onButtonClick = () => {
    axios.get("/api/user")
      .then((res) => alert(`ユーザー名:${res.data.name}`))  
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )
}

エラーハンドリング

Fetch API

Fetch APIは正常なレスポンスが返却されたかの判定をする必要があります。

Fetch API
export default function Sample () {
  const onButtonClick = () => {
    fetch(api/auth/jwt/create/
      {
        method: 'POST',
        body: JSON.stringify({ username: username, password: password }),
        headers: {
          'Content-Type': 'application/json',
        },
      }
   )
   .then((res) => {
      if (res.status === 400) {
        throw 'authentication failed'
      } else if (res.ok) {
        return res.json()
      }
    })
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )
}

axios

axiosの場合には以下のようになります。

axios
import axios from "axios";

export default function Sample() {
  const onButtonClick = () => {
    axios.post('api/auth/jwt/create/')
      .then((res) => res.data)
      .catch(() => alert("authentication failed"))
  }

  return (
    <div>
      <button onClick={onButtonClick}>ボタン</button>
    </div>
  )
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0