Как получить доступ к свойству путем выборки в javascript

#javascript #node.js

#javascript #node.js

Вопрос:

Когда я извлекаю данные на стороне сервера, я могу получить данные.Но когда я устанавливаю свойства и передаю их в

/quiz-data

 const API_KEY="https://opentdb.com/api.php?amount=1amp;type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");

module.exports={
    getQuiz:function(res){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json); 
            res.send({
                quiz,
                getNumOfQuiz:quiz.getNumOfQuiz(1),
                getCategory:quiz.getCategory(1),
                getDifficulty:quiz.getDifficulty(1),
                getQuestion:quiz.getQuestion(1),
                getAnswers:quiz.getAnswers(1)
            });
        });
    }
};
  

Когда я получаю доступ /quiz-data , я могу получить следующие данные.

 {"quiz":{"_quizzes":[{"category":"Entertainment: Film","type":"multiple","difficulty":"medium","question":"What type of cheese, loved by Wallace and Gromit, had itamp;#039;s sale prices rise after their successful short films?","correct_answer":"Wensleydale","incorrect_answers":["Cheddar","Moon Cheese","Edam"]}],"_correctAnswersNum":0},"getNumOfQuiz":1,"getCategory":"Entertainment: Film","getDifficulty":"medium","getQuestion":"What type of cheese, loved by Wallace and Gromit, had itamp;#039;s sale prices rise after their successful short films?","getAnswers":["Edam","Wensleydale","Cheddar","Moon Cheese"]}
  

Но когда я извлекаю clientside , следуя

 (()=>{
      
      const url = "/quiz-data";
      
      console.log("main.js was loaded");
      
      fetch(url)
      .then(response=>console.log(response.getCategory))
    //  .then(response => displayQuiz(response,1))

})();
  

Я страдаю от следующего.

undefined

Я установил такие свойства. почему я не смог перехватить такие свойства..

Есть ли какой-либо способ это исправить?

Спасибо

Комментарии:

1. Вы забыли вызвать response.json()

2. .then(response => response.json()).then(response => console.log(response.getCategory))

Ответ №1:

Для того, чтобы получить поля json с помощью fetch, вы должны вызвать response. json () во втором обещании затем сделайте другое обещание, чтобы получить возвращаемое значение этого, и в этом случае вы можете, наконец, прочитать свойство

Чтобы сделать это на вашем примере

 (()=>{
      
      const url = "/quiz-data";
      
      console.log("main.js was loaded");
      
      fetch(url)
      .then(response=>response. json ())
      .then(response => displayQuiz(response.getCategory,1))

})();