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>
)
}