简体   繁体   中英

How to fetch correctly from server side in Node.js

I'd like to fetch /data and serverside fetch.

But I suffered following errors.

response.getCategory is not a function

(()=>{
      const url = "/data";
            
      fetch(url)
      .then(response => {
        console.log("getCategory_main.js",response.getCategory(1));
        //displayQuiz(response,1);
      });
})();

when we access /data , serverside fetch will be functioned.

const API_KEY="https://opentdb.com/api.php?amount=1&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); 
            console.log("getCategory_model",quiz.getCategory(1));
            console.log("quiz",quiz);
            res.send(quiz);
      });
    }
};

I can get result

getCategory_model History

I should pass same data from serverside to clientside

but method access succeeded only in serverside ..

What is the cause of this? and how can I fix it? thanks..

You can't send objects with live methods over the wire as JSON. That is, if your server side Quiz object has a getCategory() method, it won't have one when you send it over to the client.

You'll need to serialize it, eg

res.send({
  quiz,
  categories: [quiz.getCategory(1)],
});

When you fetch data, your'e fetching data (usually as text). When you create a new quiz with new Quiz(json) your'e reading the json text data and using Quiz to create code from the json text.

So in your first example you should get the text result, and then evaluate the result to json so that you can use getCategory() from Quiz

const url = "/data";
fetch(url)
      .then(data => data.json())
      .then(json_text=> {
            // here you use the text and parse to JSON
         const data = JSON.parse(json_text)
            // now you can create the Quiz object
         const quiz = new Quiz(data)
         console.log("getCategory_main.js", quiz.getCategory(1));
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM