我正在开发一个客户端程序来点击帖子网址并从中获得响应 以下是我的代码
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内部服务器错误。不知道哪里出错了。