Skip to content

Files

Latest commit

 

History

History
152 lines (130 loc) · 3.43 KB

fetch.md

File metadata and controls

152 lines (130 loc) · 3.43 KB

Fetch

  • 跟 Server 獲取、提交資料的方法
  • 提供了和 web 標準一至的 Fetch API
  • 有用過 ajax 使用起來就會很上手
  • iOS 9、10、11 不支援 http,要使用 https,或是在 Info.plist 設定例外網域
    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
        <key>rn.fuyaode.me</key>
        <dict>
          <key>NSExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
        <key>localhost</key>
        <dict>
          <key>NSExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
      </dict>
    </dict>
    

使用教學

get

getData = async (page) => {
  try {
    let response = await fetch(`http://rn.fuyaode.me/users/1`);
    let responseJson = await response.json();
    console.log(responseJson);
    this.setState({
      name: responseJson.name
    })
    return responseJson;
  } catch (e) {
    console.error(e);
  }
}
getData = (page) => {
  return fetch('http://rn.fuyaode.me/users/1')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.name;
    })
    .catch((error) => {
      console.error(error);
    });
}

post

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});

form

const formData = new FormData();
form.append('id', 'A123123123');
form.append('password', '0000');
fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
  },
  body: formData,
});

檔案上傳

const formData = new FormData();
form.append('file', {
  uri: filepath,
  name: fileName,
});
fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data',
  },
  body: formData,
});

Websocket

全雙工,server 端能發訊息給 client 端,傳統 http 只能用 long polling 從 client 端去跟 server 要資料

var ws = new WebSocket('ws://host.com/path');

ws.onopen = () => {
  // connection opened
  ws.send('something'); // send a message
};

ws.onmessage = (e) => {
  // a message was received
  console.log(e.data);
};

ws.onerror = (e) => {
  // an error occurred
  console.log(e.message);
};

ws.onclose = (e) => {
  // connection closed
  console.log(e.code, e.reason);
};

延伸閱讀

API
REST
RESTful API 设计指南

  • GET(SELECT):從 server 取出資源(一項或多項)。
  • POST(CREATE):在 server 新建一個資源。
  • PUT(UPDATE):在 server 更新資源(客戶端提供改變後的完整資源)。
  • PATCH(UPDATE):在 server 更新資源(客戶端提供改變的屬性)。
  • DELETE(DELETE):從 server 刪除資源。

WebSocket