Reputation: 5299
In my router
when I access /quiz
, I'd like to render quiz.ejs
and get quiz data by doGetQuiz
to show them in quiz.ejs
I guess I must rewrite router
in some way..
following my work..
router.get('/quiz',(req,res)=>{
res.render("quiz");
});
router.get('/quiz',quizController.doGetQuiz);
Here is my controller
const Quizes = require("../models/Quizes");
module.exports = {
doGetQuiz:function(req,res,next){
Quizes.getQuiz(res);
}
};
Here is my model
const API_KEY="https://opentdb.com/api.php?amount=10&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../helpers/quiz");
module.exports={
getQuiz:function(res){
fetch(API_KEY)
.then(response => response.json())
.then(json => { const quiz = new Quiz(json);
res.json(quiz);
});
}
};
I guess I must combine them in router
..
If someone has opinion,please let me know.
Thanks
Upvotes: 0
Views: 37
Reputation: 113994
If you want to render the data directly in the ejs template you need to pass it as the second argument.
Delete the controller and modify your main route/controller to just:
// This is your main controller, routes and controllers mean the same
// thing so it is kind of stupid to have a controller call another controller
// unnecessarily
const Quizes = require("../models/Quizes");
router.get('/quiz',(req,res)=>{
Quizes.getQuiz().then(data => {
res.render("quiz", data);
});
});
Now modify your model:
getQuiz: function(res){
// THIS RETURN IS IMPORTANT to be able to use then in your controller
return fetch(API_KEY)
.then(response => response.json());
}
If instead you want to use ajax you need to give your quiz data a separate url:
router.get('/quiz-data',quizController.doGetQuiz);
Then you need to use something like fetch
or XMLHttpRequest
to get that data:
fetch('/quiz-data').then(r => r.json).then( ... )
Upvotes: 1