尽管显示在控制台日志中,但 Axios 数据仍以 undefined/NaN 形式返回

问题描述

所以我有点困惑,为什么我的数据在添加 res.render('trivia/trivia.ejs') 后立即返回未定义状态(我也尝试将其放入 axios.get 请求中)作为外部,如果它......)我什至控制台记录了一路上的每一步,它显示了正确的请求信息。 res.render 将我的数据从明确定义更改为未定义/NaN 是否有原因?


    topicsObject = {
        "art": 25,"film": 11,"geography": 22,"math" : 19,"science_computers": 18,"music": 12
    }

    let topicID = topicsObject[req.params.topic]
    console.log(`subject: ${req.params.topic} ID: ${topicID}`);

    

    // axios request
    let questions_array;
    axios.get(`https://opentdb.com/api.PHP?amount=15&category=${topicID}&difficulty=medium&type=multiple`).then((response) => {

        questions_array = response.data.results
        console.log("this is the information: ",questions_array );


        // next index of the next question within the array
        const index = parseInt(req.params.num)
        console.log(`index: ${index}`);

        const nextIndex = index + 1
        console.log(`next index: ${nextIndex}`);

        // Question Object at a given index
        let questionObject = questions_array[index]
        console.log(`the questionObject: ${questionObject}`);

        // The Trivia Question string
        let questionString = questionObject["question"]
        console.log(`the question string: ${questionString}`);

        // grabs the incorrect answers from the question object
        let incorrectAnswersArray = questionObject["incorrect_answers"]
        console.log(`Incorrect answer array: ${incorrectAnswersArray}`);

        // grabs the correct answers from the question object
        let correctAnswer = questionObject["correct_answer"]
        console.log(`Correct answer: ${correctAnswer}`);

        // concatenates the incorrect and correct answers into an array
        let answersArray = incorrectAnswersArray.concat(correctAnswer)
        console.log(`All of the answers array: ${answersArray}`);

        // Shuffle answer array

        let shuffledAnswersArray = answersArray.sort(() =>
            .5 - Math.random()
        )
        console.log(`Shuffle Answers Array: ${shuffledAnswersArray}`);
        res.render('trivias/trivia.ejs',{
                currentUser: req.session.currentUser,topic: req.params.topic,question: questionString,answers: shuffledAnswersArray,nextIndex: nextIndex
        })

    }).catch((error) => {
        console.log(error);
    })```

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)