How to send backend fetched data to frontend in Node.js

Viewed 558

I developed like MVC model in Node.js.

I would like to show data by accessing /. But now, nothing is showing in /.

Are there any wrong points? Or if you have some opinion, please let me know.

In below model, I fetch and get some data, I would like to pass this data to my frontend.

module.exports={
    getQuiz:function(){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json)});
    }
};

My controller is like this. In this controller I use getQuiz() function defined in model

const Quizes = require("../models/Quizes");

module.exports = {
    doGetQuiz:function(req,res,next){
        Quizes.getQuiz().then((result)=>{
            res.json(result);
        });
    }
};

My desired goal is to show data via /.

My router is like this.

var express = require("express");
var router = express.Router();
var quizController = require("../controllers/QuizController");

router.get('/',quizController.doGetQuiz);

module.exports = router;

Thanks!

2 Answers

You can pass in res and call its methods

module.exports={
    getQuiz:function(res){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { 
          const quiz = new Quiz(json);
          res.json(quiz);
      });
    }
};

Your controller

const Quizes = require("../models/Quizes");

module.exports = {
    doGetQuiz:function(req,res,next){
        Quizes.getQuiz(res);
    }
};

add return in your model

module.exports={
    getQuiz:function(){
      fetch(API_KEY)
      .then(response => response.json())
      .then(json => { const quiz = new Quiz(json); return quiz;});
    }
};
Related