首页 > 解决方案 > API can't handle my request because of template literals to make the API dynamic

问题描述

For a school project, I have to make a quiz app. It is possible to chose a difficulty, a category and an amount of desired questions. The api is a url which can be modified easily by changing some values. For example: https://quizapi.io/api/v1/questions?apiKey=MYAPIKEY&limit=15&difficulty=hard&category=cms. If you would just change the php to code in the url, you would get a max amount of 15 questions on a hard difficulty about HTML and CSS. I think you see where this is going.

However. I have setup my code that the difficulty, category and amount are stored in localstorage and they are fetched when the quiz is started. At the moment, I get the amout of questions I desire but I can't change my difficulty or category because probably Template Literals aren't working in a fetch api.. Maybe someone can give me an idea or maybe I'm making a mistake in my current code

let storageDif = localStorage.getItem("mD");
console.log(storageDif.toString());

let storageCat = localStorage.getItem("mC");
console.log(storageCat);

let geslideVragen = localStorage.getItem("slider");
let MAX_VRAGEN = geslideVragen;
console.log(MAX_VRAGEN);
let vragen = [];

fetch(`https://quizapi.io/api/v1/questions?apiKey=kAFKilHLeEcfLkGE2H0Ia9uTIp1rYHDTIYIHs9qf&limit=15&difficulty=hard&category=${storageCat}`)
        .then((res) => {
        return res.json();
    })
    .then((loadedQuestions) => {
        for (let i = 0; i < MAX_VRAGEN; i++) {
            vragen = loadedQuestions;
            console.log(vragen[i].question);
        };
        startGame();
    })
    .catch( err => {
        console.error(err);
    });

标签: javascriptapitemplate-literals

解决方案


推荐阅读