如何解决如何从Node.js的服务器端正确获取
我想获取/data
和服务器端获取。
但是我遇到了以下错误。
response.getCategory is not a function
(()=>{
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 History
我应该将相同的数据从serverside
传递到clientside
但是method
访问仅在serverside
中成功。.
这是什么原因?我该如何解决?谢谢。
解决方法
您不能通过在线方式将带有实时方法的对象作为JSON发送。也就是说,如果您的服务器端Quiz对象具有getCategory()
方法,则当您将其发送到客户端时,它不会有一个。
您需要对其进行序列化,例如
res.send({
quiz,categories: [quiz.getCategory(1)],});
,
获取数据时,您正在获取数据(通常是文本)。
当您使用new Quiz(json)
创建新测验时,您正在读取json文本数据,并使用Quiz
从json文本创建代码。
因此,在第一个示例中,您应该获取文本结果,然后将结果评估为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));
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。