【问题标题】:Get a javascript object's methods with http get request?使用 http get 请求获取 javascript 对象的方法?
【发布时间】: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


    【解决方案1】:

    您不能通过 http 协议发送函数。如果您希望使用相同的构造函数和方法,我的建议是,将所有这些代码移动到没有任何环境(nodejs、浏览器)引用的文件中,并在两个地方使用相同的文件。

    【讨论】:

    • 谢谢!如果我要将代码保存在单独的文件中,我想我可以在对象之外创建更多的 put/get 请求处理程序,这些处理程序可以更新/检索 server.js 中的对象属性(例如添加子站点和获取标题)文件。这是一个不错的选择吗?
    • 是的,这是个好主意。你应该这样想,你将通过 http 协议发送的对象应该只是一个简单的对象,没有函数,只是数据。组织代码的方法有很多种,但毫无疑问,您必须牢记的一件事是按关注点分开代码。也许,请阅读以下内容:medium.com/datadriveninvestor/…
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多