【问题标题】:Using java script functions in node js在节点 js 中使用 javascript 函数
【发布时间】:2020-02-01 14:01:27
【问题描述】:

我正在使用下面的 JS 库在 NodeJS 中将 JSON 转换为 XML。

XML.ObjTree

我创建了一个名为XMLJSONParser.js 的JS 文件,并在其中添加了XML.ObjTree 内容,如下所示。

module.exports = function () { XML.ObjTree = function () { return this; }; ................ More code };

在控制器中,我有以下代码来进行转换。

const XMLs = require('../common/XMLJSONParser');
router.post('/', async (req, res) => {
    try {
       var { tasks } = req.body;
        var xotree = new XMLs.XML.ObjTree();
        var tree1 = {tasks}
        var xml1 = xotree.writeXML( tree1 );
        alert( "xml1: "+xml1 );
     }

调用时出现异常

消息:“无法读取未定义的属性‘ObjTree’” 堆栈:“类型错误:无法读取属性

从 Node JS 调用 JS 文件的方式是否正确?

我能够正确运行并获得https://js.do 中的输出。

【问题讨论】:

  • 您作为第一个 sn-p 发布的 exports 不知何故不完整,但是,看起来您正在导出 一个函数。但是,当您导入它时,您希望它是一个具有.XML 属性的对象。如果是这样,该函数肯定不具有该属性,因此您不能进一步要求.ObjTree()
  • 删除 module.exports = function () { 并在你的 XMLJSONParser.js 文件底部添加这个 module.exports = XML; 你可以这样做 const XML = require('../common/XMLJSONParser'); XML.ObjTree();

标签: javascript node.js jsonconvert xmlconvert


【解决方案1】:

XMLundefined 所以定义XML

module.exports = function () {
 let XML = {};
 XML.ObjTree = function () {
        return this;
    };
................ More code
};

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    相关资源
    最近更新 更多