我正在呼叫 API 并通過其分頁獲取資料。但是,當我到達最后一頁時,給我最后一頁的物件是空的,并且拋出以下錯誤:TypeError: Cannot convert undefined or null to object此外,我沒有來自最后一頁的任何資料。
這是我得到的分頁資訊:
{"count":100,"total":545,"_links":
{
"self":{
"href":"\/candidates?page=0&per_page=100"
},
"next":{
"href":"\/candidates?per_page=100"
},
"last":{
"href":"\/candidates?page=6&per_page=100"
}
},
這是我用來獲取資料的代碼:
function allcandidates() {
const url = "https://api.catsone.com/v3/candidates";
const params = {
'muteHttpExceptions': true,
'method': 'GET',
'redirect': 'follow',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Token ' API_KEY
}
};
let pageNum = 1;
let lastPgNo;
let data = {}, output = [];
do {
let currentUrl = url '?' 'per_page=100' '&' 'page=' pageNum;
//One of their URL parameter is "per_page", which is 25 result/page and it go up to 100. I'm not sure if the fact that the last page doesn't have all 100 results may result in an error, too.
const response = UrlFetchApp.fetch(currentUrl, params);
const respCode = response.getResponseCode();
if (respCode != 200) {
Browser.msgBox('The server seems to be temporarily down. Please try again later.');
return;
}
//Gets the last page number
const getText = response.getContentText();
const lastPageObj = JSON.parse(getText)['_links']['last'];
const lastPgVal = Object.values(lastPageObj); //This is where the error occurs
const lastPgText = lastPgVal.toString();
lastPgNo = Number(lastPgText.split('?page=').pop().split('&')[0])
//Gets current page
const currentPageObj = JSON.parse(getText)['_links']['self'];
const currentPgVal = Object.values(currentPageObj);
const nextPgText = currentPgVal.toString();
var currentPgNo = Number(nextPgText.split('?page=').pop().split('&')[0])
const dataSet = JSON.parse(getText)['_embedded']['candidates'];
for (let i = 0; i < dataSet.length; i ) {
data = dataSet[i];
output.push([data.id]);
}
pageNum = pageNum 1;
} while (pageNum <= lastPgNo);
}
uj5u.com熱心網友回復:
您可以使用if陳述句和continue. IE替換
const lastPgVal = Object.values(lastPageObj);
經過
if(lastPageObj){
const lastPgVal = Object.values(lastPageObj);
} else {
continue;
}
另一種選擇是使用 try...catch
資源
- https://developer.mozilla.org/en-US/docs/Glossary/Truthy
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410885.html
標籤:
