我在 React 應用程式中使用 fetch API 來檢索和顯示一些測驗問題。這是我的 url 端點:https ://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple
我注意到:
- 當我在“?”之前拼錯部分 URL 時 然后回應不會回來。示例:https ://opentdb.com/api.ph?amount=${amount}&difficulty=${difficulty}& (缺少 php 的“p”)
- 當我在“?”之后拼錯部分網址時 然后,有時我得到一個空陣列,有時我得到資料。如何使用錯誤的 URL 取回資料?示例:https ://opentdb.com/api.php?amoun=${amount}&difficulty=${difficulty}&type=multiple (金額中缺少“t”)
我還沒有部署應用程式,我正在使用 vsc 并運行 npm start 來開發應用程式。URL是否有可能自動更正?或者它被快取了?
我的代碼:
export const fetchQuizQuestions = async (
amount: number,
difficulty: Difficulty
) => {
const endPoint = `https://opentdb.com/api.php?amount=${amount}&difficulty=${difficulty}&type=multiple`;
try {
const response = await fetch(endPoint);
console.log(response);
const data = await response.json();
console.log(data);
if (data.results.length === 0) {
throw new Error("The part after ? contains some mistake");
}
//below I create the new property "all_answers" and make sure the answers order is never the same
return data.results.map((question: Question) => ({
...question,
all_answers: shuffleArray([
...question.incorrect_answers,
question.correct_answer,
]),
}));
} catch (error: any) {
console.log(error.name);
console.log(error.message);
}
};
uj5u.com熱心網友回復:
在?它是網址之前。所以如果你在那里犯了錯誤,基本上就像給不同的地址寄信一樣,所以你不會得到任何答復。
在?它之后是查詢字串。所以你要一個帶有一些引數的結果(你的查詢)所以如果你說“好的,給我發回數量=XXX的答案”但是你拼錯amount了,就像“好的,給我發回答案”,因為你不再要求amount了(但這amoun對端點來說什么都不是)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527171.html
標籤:反应网址错误处理试着抓获取 API
