简体   繁体   English

如何从 Node.js 中的服务器端正确获取

[英]How to fetch correctly from server side in Node.js

I'd like to fetch /data and serverside fetch.我想获取/data和服务器端获取。

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.当我们访问/data时,服务器端 fetch 将起作用。

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我应该将相同的数据从serverside传递到clientside

but method access succeeded only in serverside ..但是method访问仅在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.您不能通过 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.也就是说,如果您的服务器端测验 object 有一个getCategory()方法,那么当您将它发送到客户端时它不会有一个。

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.当您使用new Quiz(json)创建新测验时,您将阅读 json 文本数据并使用Quiz从 json 文本创建代码。

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因此,在您的第一个示例中,您应该获取文本结果,然后将结果评估为 json 以便您可以使用测验中的getCategory()

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));
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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