我想要获取/data
和服务器端获取。
但我犯了以下错误。
Response.GetCategory不是函数
(()=>{
const url = "/data";
fetch(url)
.then(response => {
console.log("getCategory_main.js",response.getCategory(1));
//displayQuiz(response,1);
});
})();
当我们访问/data
时,服务器端提取将起作用。
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);
});
}
};
我能得到结果
GetCategory_Model历史记录
我应该将相同的数据从serverside
传递到clientside
但方法
访问仅在服务器端
中成功。
这是什么原因造成的呢? 我该怎么修复它呢? 谢谢。。
您不能将带有活动方法的对象作为JSON通过网络发送。 也就是说,如果您的服务器端Quiz对象有一个getCategory()
方法,那么当您将它发送到客户端时,它将没有一个方法。
您将需要序列化它,例如。
res.send({
quiz,
categories: [quiz.getCategory(1)],
});
当您获取数据时,您正在获取数据(通常是文本)。 当您使用new quiz(json)
创建新的测试时,您将读取json文本数据并使用quiz
从json文本创建代码。
因此,在第一个示例中,您应该获得文本结果,然后将结果计算为json,以便可以使用Quiz中的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));
});