Fetch()関数の使い方(3)

1536 ワード

fetch()関数-メソッドはgetですが、パラメータを渡す必要があります.
get例は3というuser idをpathに渡す.でもpathじゃなくquery stringかも
설명: 유저 정보를 가져온다.
base url: https://api.google.com
endpoint: /user
method: get
query string: ?id=아이디
응답형태:
    {
        "success": boolean,
        "user": {
            "name": string,
            "batch": number
        }
    }
fetch(' https://api.google.com/user?id=3' )
.then(res => res.json())
.then(res => {
if (res.success) {
console.log(${res.user.name}へようこそ);
}
});
fetch()関数-res.json()の意味
fetch('https://api.google.com/user', {
    method: 'post',
    body: JSON.stringify({
        name: "yeri",
        batch: 1
    })
  })
  .then(res => res.json())   // 왜 then이 두개고 res.json() 은 뭔지?
  .then(res => {
    if (res.success) {
        alert("저장 완료");
    }
  })
最初のthen関数に渡されるパラメータresは、HTTP通信要求および応答からの応答情報を含むオブジェクトである.応答オブジェクトと呼ばれます.
コンソールを表示すると、バックエンドで渡される応答ボディ(実際のデータ)は表示されません.つまり、上のコードではJSONデータはコンソールに書き込まれません.
応答として受信したJSONデータを使用するには、応答オブジェクトのjson関数を呼び出して返さなければなりません.次に、2番目のthen関数は、bodyに応答するデータを受信する.
fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));