1

我将节点中的 post 方法公开为

function onRequest(request, response) {
    var postData='';
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    if(request.method==="POST"){
        request.setEncoding("utf8");
        console.log('in post');
        request.addListener("data", function(postDataChunk) {
            postData += postDataChunk;
            console.log("Receiving POST data chunk '"+postDataChunk + "'.");
        });
        request.addListener("end", function() {
           console.log("Received POST data ");
           console.log(postData);
        });    
    }
}

我希望控制台日志是 xml string 。

<ContainerItem>
          <Id>Id</Id>
          <Name>Name</Name>
          <Description>Description</Description>
          <Type>Type</Type>
  </ContainerItem>

但它给了我输出:

text=%3CContainerItem%3E%0D%0A++++++++++%3CId%3EId%3C%2FId%3E%0D%0A++++++++++%3CName%3EName%3C%2FName%3E%0D%0A++++++++++%3CDescription%3EDescription%3C%2FDescription%3E%0D%0A++++++++++%3CType%3EType%3C%2FType%3E%0D%0A%3C%2FContainerItem%3E

我怎样才能得到这个作为 XML 字符串?这样我就可以使用 xml2js 库对其进行解析。

4

1 回答 1

0

数据是以querystring格式接收的,接收时是URL编码的,所以需要解码。您可以为此目的使用本机查询字符串模块:

var qs = require('querystring');
var str = 'text=%3CContainerItem%3E%0D%0A++++++++++%3CId%3EId%3C%2FId%3E%0D%0A++++++++++%3CName%3EName%3C%2FName%3E%0D%0A++++++++++%3CDescription%3EDescription%3C%2FDescription%3E%0D%0A++++++++++%3CType%3EType%3C%2FType%3E%0D%0A%3C%2FContainerItem%3E';

var xml = qs.parse(str);
// data.text

解析后的查询字符串现在位于一个对象中,因此您现在可以将其传递data.text给您的 XML 解析器:

var parseString = require('xml2js').parseString;
parseString(xml, function(err, result) {
  // parsed XML is in result
});
于 2013-10-03T13:25:51.653 回答