3

我正在开发一个客户端程序来点击一个帖子网址并从中获取响应下面是我的代码

var http = require('http');
var fs = require('fs');

var postData = "<?xml version = '1.0' encoding = 'utf-8'?><REST><Contact>aa</Contact></REST>";

fs.readFile('SampleData.xml', 'utf8', function (err, fileData)
{
if (err)
{
    return console.log(err);
}
else
{
    console.log("\n Data : \n\n" +fileData);

    var options = {
        host: 'kkk',
        port: 1,
        path: '/root',
        method: 'POST',
        headers: {
            "Content-Type" : 'application/xml'
        }
    };

    var reqClient = http.request(options, function(res)
    {
        res.setEncoding('utf8');
        res.on('data', function (chunk)
        {
            //console.log('BODY: ' + chunk);
        });
    });

    //Posts the data to the Server
    reqClient.write(postData);
    reqClient.end();

    reqClient.on('response', function (response)
    {
        response.on('data', function (chunk)
        {
            //console.log(response.statusCode + "\n");
            //console.log(response.headers);
            console.log("\n" + 'RESPONSE: ' + chunk);
        });
    });
    }
 });

我尝试从文件中读取 xml 数据,而且我还直接在 req.write 中传递了数据。这两次都只是抛出错误,因为 xml 是作为字符串传递的。我需要一个解决方案在传递之前将字符串转换为 xml .我被困在这里。任何帮助都会很有帮助。

我也尝试了一种新方法,请在代码下方找到

var http = require('http');
var body='<?xml version="1.0" encoding="utf-8"?>'+
'<REST><ListOfLN_Interface>'+
'<Contact>123304</Contact>'+
'</ListOfLN_Interface></REST>';



var postRequest = {
host: "hhhh",
path: "/Contact",
port: 01,
method: "POST",
headers: {

    'Content-Type': 'application/xml',
    'Content-Length': Buffer.byteLength(body)
}
}; 

var buffer = "";

var req = http.request( postRequest , function( res )    {

console.log( res.statusCode );
console.log( res.headers);
var buffer = "";
var chunks = [];
res.on('data', function (data) {
    chunks.push(data);
});
res.on('end', function(){
    var body1 = Buffer.concat(chunks).toString();

    //var xmlDoc = libxmljs.parseXml(body);
   // var status = xmlDoc.get('//Status').text();
    //var ticket = xmlDoc.get('//Incident_ID').text();
    console.log(body1);
});
 //res.on( "data", function( data ) { buffer = buffer + data; } );
// res.on( "end", function( data ) { console.log( buffer ); } );

});

req.write( body );
req.end();

这给我带来了 500 个内部服务器错误。不知道哪里出错了。

4

0 回答 0