Node.js xml2js解析器未定义

时间:2017-10-19 14:38:21

标签: javascript node.js xml httprequest xml2js

所有

我试图通过xml2js解析HTTP响应XML并遇到错误。我正在尝试按照这些说明操作:https://programmerblog.net/parse-xml-using-nodejs/

我确实安装了模块,似乎运行正常。

我得到的错误。

    parser.parseString(soapreplyx, function (err, result) {
    ^
ReferenceError: parser is not defined

我的应用代码看起来像这样。

// APP - INCLUDE
const express = require('express')
const path = require("path")
const bodyParser = require("body-parser")
const hbs = require('hbs')
var xml2js = require('xml2js');
var parser = new xml2js.Parser();

// APP - DEFINITION
const app = express()

// APP - BUILD
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.engine('html', require('hbs').__express);
app.set('view engine', 'html');

// EXPRESS ROUTE - INDEX
app.get('/', function (req, res) {
  res.render(path.join(__dirname+ '/views/index.html'), {
    'title': 'CUCM 2.0'
  });
})

// EXPRESS ROUTING - INCLUDE - CUCM MAPPER
var routingextensions = require(__dirname+ '/routes/cucmmapper.js')(app);

// APP - START
app.listen(3000, function () {
  console.log('CUCM 2.0 listening on port 3000!')
})

Extra Express Route code。

module.exports = function (app) {
  // FORM - SUBMIT - CUCMMAPPER
  app.post('/cucmmapper/submit', function (req, res) {

    // FORM - DATA COLLECTION
    var cucmpub = req.body.cucmpub;
    var cucmversion = req.body.cucmversion;
    var username = req.body.username;
    var password = req.body.password;

    // JS - VARIABLE DEFINITION
    var authentication = username + ":" + password;
    var soapreplyx = '';
    var cssx = '';
    //var parser = new xml2js.parser();

    // HTTP.REQUEST - BUILD CALL
    var https = require("https");
    var headers = {
      'SoapAction': 'CUCM:DB ver=' + cucmversion + ' listCss',
      'Authorization': 'Basic ' + new Buffer(authentication).toString('base64'),
      'Content-Type': 'text/xml; charset=utf-8'
    };

    // SOAP - AXL CALL
    var soapBody = new Buffer('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.cisco.com/AXL/API/11.5">' +
      '<soapenv:Header/>' +
      '<soapenv:Body>' +
      '<ns:listCss sequence="?">' +
      '<searchCriteria>' +
      '<name>%</name>' +
      '</searchCriteria>' +
      '<returnedTags uuid="?">' +
      '<name>?</name>' +
      '<description>?</description>' +
      '<clause>?</clause>' +
      '</returnedTags>' +
      '</ns:listCss>' +
      '</soapenv:Body>' +
      '</soapenv:Envelope>');

    // HTTP.REQUEST - OPTIONS
    var options = {
      host: cucmpub, // IP ADDRESS OF CUCM PUBLISHER
      port: 8443, // DEFAULT CISCO SSL PORT
      path: '/axl/', // AXL URL
      method: 'POST', // AXL REQUIREMENT OF POST
      headers: headers, // HEADER VAR
      rejectUnauthorized: false // REQUIRED TO ACCEPT SELF-SIGNED CERTS
    };

    // HTTP.REQUEST - Doesn't seem to need this line, but it might be useful anyway for pooling?
    options.agent = new https.Agent(options);

    // HTTP.REQUEST - OPEN SESSION
    let soapRequest = https.request(options, soapResponse => {
      soapResponse.setEncoding('utf8');
      soapResponse.on('data', chunk => {
        soapreplyx += chunk
      });
      // HTTP.REQUEST - RESULTS + RENDER
      soapResponse.on('end', () => {
        parser.parseString(soapreplyx, function (err, result) {
          var cssx = result['return']['css'];
          res.render('cucmmapper-results.html', {
            title: 'CUCM 2.1',
            soapreply: soapreplyx,
            css: cssx,
        })
        });
      });
    });

    // SOAP - SEND AXL CALL
    soapRequest.write(soapBody);
    soapRequest.end();
  });
}

这也是我从HTTPRequest获取的XML的一个示例。

<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns:listCssResponse xmlns:ns="http://www.cisco.com/AXL/API/11.0">
<return>
<css uuid="{E85C54E1-5737-7516-FFFC-14E97B1D0504}">
<description>description</description>
<clause>blablabla</clause>
<name>name</name>
</css>
<css uuid="{AFFC55A7-CD16-E250-09E8-9A12ABBE0C9E}">
<description>description</description>
<clause>blablabla</clause>
<name>name</name>
</css>

我真的希望我能正确设置所有内容,但对于JS的所有内容都是新手。任何建议或帮助都是非常受欢迎的。感谢您花时间寻找并帮助我!

1 个答案:

答案 0 :(得分:0)

在node.js中,每个文件都是自己的模块。这意味着在一个模块中定义的变量不是全局变量,除非您明确导出它们,否则不会在其他文件中自动提供。

所以在您的代码中定义:

var xml2js = require('xml2js');
var parser = new xml2js.Parser();

在您的应用模块中,您无法在额外路线模块中访问它,这就是错误所说的内容。解决方案是简单地将定义放在其他文件中:

var xml2js = require('xml2js');
var parser = new xml2js.Parser();

module.exports = function (app) {
  // FORM - SUBMIT - CUCMMAPPER
  app.post('/cucmmapper/submit', function (req, res) {
  // etc...
}