難度: 進階
目標: 加上登入功能與 JWT 驗證
專案: https://github.com/agileworks-tw/RN_Todo_Sample
練習:
- SignIn 畫面加入 password 輸入欄位
- Sign in 時送出
localhost:3000/login
API
// type: 'POST'
// body:
{
"username": "rn-tw",
"password": "rn-tw"
}
request 範例
fetch("http://localhost:3000/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
username: "rn-tw",
password: "rn-tw"
})
})
.then(res => res.json())
.then(result => console.log(result));
-
透過請求的 response 確認是否登入成功 (res.success),若成功則將 jwt token 寫入 AsyncStorage , 連同 username 資料一併跳轉至 ToDoList 頁面
-
依照 JWT 標準將 ToDoList API 頁面的 get, create, delete API 加上 Authorization token,讓 API 可以成功運作
- ToDoList RESTful API server
cd ~/workspace
git clone https://github.com/agileworks-tw/express-example
cd express-example
git checkout practice/jwt
yarn
- ToDoList React Native Sample
cd ~/workspace
git clone https://github.com/kyoyadmoon/RN_Todo_Sample
cd RN_Todo_Sample
git checkout feature/async-storage
yarn
git add .
git reset --hard HEAD
cd ~/workspace/express-example
npm start
cd ~/workspace/RN_Todo_Sample
# 確認在 feature/add-todo-list branch
# 這會執行 packager server
react-native start
# 需要另外開一個 terminal
react-native run-android
# 模擬器連接 3000 port
adb reverse tcp:3000 tcp:3000