微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决尽管显示在控制台日志中,但 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 举报,一经查实,本站将立刻删除。