【发布时间】:2019-11-24 18:01:35
【问题描述】:
我的服务器文件中有一个对象构造函数,它构造一个包含一些函数的对象。当我在 server.js 文件中使用 Express 发送对象并在 app.js 文件中使用 axios get 请求检索它时,该对象的功能丢失了。为什么是这样?如何使用对象发送/获取函数?
我正在使用 React(不过我认为这并不重要)。这些函数允许我更新对象的数据。该对象应该充当其他站点的文件夹。
服务器.js
const sites = []; //array that holds objects
//this function generates a random ID for the object
const makeID = function () {
return '_' + Math.random().toString(36).substr(2, 9);
};
//Here is my object (site constructor)
const makeSite = (customerInfo={}, parent=undefined, isMain=false, isFile=false, subsites=[]) => {
const site = {
customerInfo,
isMain,
subsites,
isFile,
id: makeID(),
get title() {
if (!this.isMain) {
return `${parent.title}/${this.customerInfo.name}`;
} else {
return this.customerInfo.name;
}
},
addSubsites(subsite_arr) {
this.subsites += subsite_arr;
}
};
return site;
}
//Here is a function that allows me to make a default object and add it to the array of sites
publishSite = (info) => {
const newSite = makeSite(info, undefined, true, false); //calling constructor
newSite.addSubsites([ //default subsites
makeSite({name: 'Scope'}, newSite),
makeSite({name: 'Notes'}, newSite),
makeSite({name: 'Material'}, newSite),
makeSite({name: 'Changes'}, newSite),
])
sites.unshift(newSite);
}
publishSite({name: "RED"}); //adds object to sites array
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/sites', (req, res) => {
res.send(sites); //sends sites array (see top of code)
});
App.js
//function that gets sites array and logs it to console/updates state
async refreshSites() {
const {data} = await Axios.get('/sites');
console.log(data);
this.setState({sites: data})
}
当我运行应用程序时,这会记录到控制台
[{…}]
0:
customerInfo: {name: "RED"}
id: "_pppxh5zy6"
isFile: false
isMain: true
subsites: (4) [{…}, {…}, {…}, {…}]
title: "RED"
__proto__: Object
length: 1
它包含除了方法之外的所有信息,并且调用方法会引发错误。还值得注意的是,即使我直接更改对象 customerInfo.name,对象的“title”属性也不会改变。如何发送对象的方法并在 app.js 中调用它们(如 addSubsites)?
【问题讨论】:
标签: javascript json express http axios