0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでのAPI取得

0
Posted at

JavaScriptでのAPI取得についての勉強の備忘録。
fetchとAxiosについてまとめました。

fetchについて

記述方法

const data = fetch("url",{
    method:"GET""POST"など
    header:{ ~ }
    body: ~
})

ヘッダーの設定

サーバーにメタデータ(データの種類や条件)を伝える

const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ username: "example" }),
  // …
});

Headerオブジェクトの作成

const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: myHeaders,
  body: JSON.stringify({ username: "example" }),
  // …
});

Requestオブジェクトの作成

URL, method,header,bodyの属性を持ったRequestオブジェクトをつくってそれを

fetch(Requestオブジェクト)

の形で送ることが可能。

const request1 = new Request("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ username: "example1" }),
});

const request2 = new Request(request1, {
  body: JSON.stringify({ username: "example2" }),
});

Axiosについて

Fetchとの違い

AxiosはPOST時などにHeaderの設定不要。
GET時、自動でデータをjson形式にしてくれる。
エラー対策が楽(Fetchはnot foundとかでエラー投げてくれない)。

記述方法

AxiosはPromiseオブジェクトを返す⇒ async/awaitをもちいて記述

const AxiosTest=async(url)=>{
    try{
       const data=await axios.get(url)
       //get中にエラーが起こったら自動でcatchに飛んでくれるため、エラー処理不要
        return "success"
    }catch(error){
        console.log(error.message)
        return error.message
    }
    
}

POST時、headerの記述不要。自動でわかってくれる。


const data={"first":"Shunsuke","last":"mikami"}

const SendData=async(data)=>{
    try{
        const res=await axios.post("http://localhost:3000",//url
        data, //body部分
        { //第3引数にはheadersを書く。認証などの自動補完されな情報は別途書く必要あり
          headers: {
            Authorization: "Bearer token",
        })
        console.log(res.data)
    }
    catch(error){
        console.log(error)
    }
    
}

axios.create

インスタンスをつくって共通する設定をまとめておける

//new axios.create({baseURL,headersなどの属性をもつオブジェクト})
const commonData=new axios.create({
    baseURL:"http://localhost:3000",
    headers:{
        "Content-Type":"application/json",
        "Authorization":"Bearer token",
    }
})

const SendData=async(data)=>{
    //第1引数にはエンドポイントのみ記載、
    const res=await commonData.post("/test",data)
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?