如何将 javascript 对象文字从 Node 后端发送到浏览器前端?

How to send javascript object literals from a Node backend to the browser frontend?

我正在使用 Node,其中我有 JavaScript 个带有后端方法的对象文字,例如:

const report = {
    id: 1,
    title: 'Quarterly Report for Department 12345',
    abstract: 'This report shows the results of the sales and marketing divisions.', 
    searchText: function () {
        return this.title + '|' + this.abstract;
    }
};

我想通过 AJAX 将这些对象文字发送到前端,并能够像在后端一样调用这些对象的方法。

但是即使我可以在没有 JSON.stringify() 的情况下将对象发送到前端,当它们到达我的前端时它们仍然被转换为普通的 JSON:

我是不是遗漏了什么,或者没有办法将完整的对象文字从后端发送到前端。我正在使用 Axios。

But even though I can send the objects to the frontend without JSON.stringify(),

听起来您 正在 使用 JSON.stringify ……只是间接地(通过图书馆)。

JSON 没有 function 数据类型。所以你不能只是使用JSON.

你有几个选择。

按照我推荐的顺序列出。


解决方法

在你的例子中,你的函数很简单 return this.title + '|' + this.abstract; 所以你可以用字符串替换它:

const report = {
    id: 1,
    title: 'Quarterly Report for Department 12345',
    abstract: 'This report shows the results of the sales and marketing divisions.', 
    searchText: 'Quarterly Report for Department 12345|This report shows the results of the sales and marketing divisions.'
    }
};

您可以使用 replacer argument of JSON.stringify 为对象上的任何方法自动执行此操作。

这是最简单的选项,但会导致数据不会动态更新,因此可能不适合您的需要。

使用客户端代码添加方法

发送一个简单的对象,没有方法但是有描述类型的字段 个对象。

然后在客户端对其进行充气:

const type = ajaxResponse.type;
const Constructor = collectionOfConstructorFunctions[type];
const data = new Constructor(ajaxResponse.data);

改为发送JavaScript

您可以使用 JSONP 而不是 Axios。

响应将是 application/javascript 而不是 application/json,因此您可以在返回的数据中对函数表达式进行编码。

我不推荐这个选项。

对 JSON 中的函数进行编码,然后将它们包含在客户端

这太可怕了。

const report = {
    id: 1,
    title: 'Quarterly Report for Department 12345',
    abstract: 'This report shows the results of the sales and marketing divisions.',
    searchText: "return this.title + '|' + this.abstract;"
}

然后,在客户端上:

report.searchText = new Function(report.searchText);
console.log(report.searchText());

这实际上是在使用 eval。别这样。