我的服务器文件中有一个对象构造函数,它构造一个包含一些函数的对象。当我在server.js文件中发送带有Express的对象并在app.js文件中使用axios请求检索它时,对象的函数就会丢失。为什么会这样呢?如何使用对象发送/获取函数? 我正在使用React (我认为这并不重要)。这些函数允许我更新对象的数据。该对象应该用作其他站点的文件夹。
Server.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,对象的“标题”属性也不会改变。如何发送对象的方法并在app.js (如addSubsites)中调用它们?
发布于 2019-07-16 04:13:28
您不能通过http协议发送函数。如果您希望使用相同的构造函数和方法,我的技巧是,将所有这些代码移动到没有任何环境(nodejs,browser)引用的文件中,并在两个地方使用相同的文件。
https://stackoverflow.com/questions/57049821
复制相似问题