--- tags: API --- # API練習 TodoList(未完成,等讀完promise.all後補上):使用axios 當我們拿到API時候時,都不要先急著操作,先試著測試看看API是否可使用 >使用六角學院所提供的API去做串接 >使用工具:[swagger](https://todoo.5xcamp.us/api-docs/index.html)、postman(網址請求測試軟體) >練習連結:[GitHub](https://github.com/IreneLee18/api-todoList)、[GitHubPage](https://irenelee18.github.io/api-todoList/) >未串接API的步驟:[TodoList](https://hackmd.io/Fl84zcAYQlaxAsrhNreKaA) >`由於步驟與未串接的大同小異,只差在API串接的部分,所以主要會寫API的筆記,如果之後自己看不懂那就...自己再慢慢看程式碼研究唄!祝福未來的我` 使用postman測試: 1. 輸入格式`(每個API都有屬於自己的jsno格式,所以要看後端工程師給我們怎樣的來再來做操作,這裡是用swagger格式)` ![](https://i.imgur.com/g0HuVxS.png) 2. 金鑰加入位置 ![](https://i.imgur.com/Iq3iPsc.png) 3. 可查看其他種如何載入headers方式 ![](https://i.imgur.com/bqDCNQJ.png) ```javascript= methods: { // 登入 login() { axios .post(`${this.apiUrl}/users/sign_in`, { user: { email: this.email, password: this.password, }, }) .then((res) => { axios.defaults.headers.common["Authorization"] = res.headers.authorization; this.myTodoName = res.data.nickname; }) .catch((err) => console.log(err.response)); }, ``` ## headers.authorization :star: ==每一個使用者都有屬於自己的金鑰(headers.authorization)== 1. 先在登入位置取得到自己的金鑰,寫法: `第14行,取得到金鑰後,並賦予到token上` ```javascript= data() { return { token: '', } }, methods: { login() { axios .post(`${this.apiUrl}/users/sign_in`, { user: { ... }, }) .then((res) => this.token = res.headers.authorization) .catch((err) => console.log(err.response)); }, } ``` 2. 將金鑰放入headers中,使其他方法可以成功取得專屬於自己的資料 `第5-7行程式碼很重要❗️沒有他就取不到自己的資料` ```javascript= // 取得todo renderData() { axios .get(`${this.apiUrl}/todos`,{ headers: { 'Authorization': this.token } }) .then((res) => this.allData = res.data.todos) .catch((err) => console.log("get", err.response)); }, ``` ## 刪除所有已完成Todo:使用Promise.all >老師說:我們的API無法同時刪除多筆,只能一次單筆單筆的刪除,所以這裡可以使用promise.all來發出請求「同時刪除所回傳的值」 > >參考文件: >[Promise.all() 與 async/await(和 axios)](https://linxinemily.github.io/2019/06/30/Promise-all%E8%88%87async-await%EF%BC%88%E5%92%8Caxios%EF%BC%89/) >>當所有的 Promise 都被 resolve 後才會回傳 resolve,其值會是全部的 Promise 處理完後所回傳的 resolve 值所組成的陣列。但若其中有一個 Promise 被 reject 就會直接拋出該 Promise 所回傳的錯誤。 :::spoiler 完整程式碼 ```javascript= deleteAll() { // 首先先取得到所有已完成的id this.doneData.forEach((item) => { this.deleteData.push(item.id); }); this.renderData(); // 使用promise.all去取得所有已完成(成功才會繼續執行) Promise.all(this.deleteData) .then((res) => console.log("deleteAll", res)) .catch((err) => console.log(err.response)); // 跑回圈取出所有已完成的id for (let i = 0; i < this.deleteData.length; i++) { axios .delete(`${this.apiUrl}/todos/${this.deleteData[i]}`) .then((res) => { this.renderData(); this.deleteData = []; }) .catch((err) => console.log(err.response)); } }, ``` ::: + promise.all ```javascript= // 使用promise.all去取得所有已完成(成功才會繼續執行) Promise.all(this.deleteData) .then((res) => console.log("deleteAll", res)) .catch((err) => console.log(err.response)); ``` + 跑回圈取出所有已完成的id + 如果i < 已完成資料長度,i就+1 `這裡不是「<=」&「i 從 0 開始」,原因是:假設長度是3,i會加到3為止才會跳出,i會是「0、1、2、3」,這樣就多跑一次而導致找不到該id的陣列索引值(索引值都是從0開始的)` + ==第三行程式碼==:將上面跑回圈的i(索引值)帶入到this.deleteData中,就可以取出該索引值的id,這樣就可以一次一次(跑回圈)的把所有已完成的id給帶入進去並刪除 ```javascript= for (let i = 0; i < this.deleteData.length; i++) { axios .delete(`${this.apiUrl}/todos/${this.deleteData[i]}`) .then((res) => { this.renderData(); this.deleteData = []; }) .catch((err) => console.log(err.response)); } ``` ## 監聽帳號&密碼&匿名 由於寫在同頁面會出錯是正常的,要寫在不同頁面才不會繼續監聽,但因為還沒改寫完成所以先暫時先用這個,等改寫完成再補上 > localStorage[詳細筆記](https://hackmd.io/4vng3PZvTz2WWZUWXt7Zlg?both) 分三個頁面:需要加上localstorage才可以取得到token,但課程上沒有教,所以要自己研究 資料一 https://developer.mozilla.org/zh-TW/docs/Web/API/Window/localStorage 資料二 https://medium.com/%E9%BA%A5%E5%85%8B%E7%9A%84%E5%8D%8A%E8%B7%AF%E5%87%BA%E5%AE%B6%E7%AD%86%E8%A8%98/javascript-localstorage-%E7%9A%84%E4%BD%BF%E7%94%A8-e0da6f402453 ```javascript= watch: { // 監聽 email email() { const isMail = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z]+$/; if (!isMail.test(this.email) || this.email === "") { this.emailError = true; } else { this.emailError = false; } }, // 監聽 密碼 password() { if (this.password.length < 6) { if (this.password === "") { this.passwordError = true; } } else { this.passwordError = false; } }, // 監聽 再次輸入密碼 passwordAgain() { if (this.passwordAgain != this.password) { if (this.passwordAgain === "") { this.passwordAgainError = true; } } else { this.passwordAgainError = false; } }, // 監聽 使用者名稱 userName() { if (this.userName === "") { this.userNameError = true; } else { this.userNameError = false; } }, }, ```