Skip to content

Instantly share code, notes, and snippets.

@takunagai
Last active May 29, 2022 23:34
Show Gist options
  • Save takunagai/6d819e3b8b3a9991287c4cffdc13a31e to your computer and use it in GitHub Desktop.
Save takunagai/6d819e3b8b3a9991287c4cffdc13a31e to your computer and use it in GitHub Desktop.
[Get data from API with axios] #JavaScript #axios
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/todos'
async function getTodo(id) {
try {
const response = await axios.get(`${url}/${id}`)
// console.log(response)
return (response.data)
}
catch (error) {
// console.error(error)
return 'データ取得失敗'
}
finally {
console.log('必ず実行(データ取得中に先に呼ばれる)')
}
}
console.log(await getTodo(1))
console.log(await getTodo(2))
console.log(await getTodo(-1)) // 失敗
import axios from 'axios'
const url = 'https://jsonplaceholder.typicode.com/todos/1'
axios.get(url)
.then((response) => { // 成功のとき
console.log('成功: ', response.data)
})
.catch((error) => { // エラーの時
// console.log('エラー: ', error)
console.log('データ取得失敗')
})
.then(() => { // 必ず実行
console.log('必ず実行(最後に呼ばれる)')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment