如何在 node.js http.request 中发布 XML 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14018269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to post XML data in node.js http.request
提问by mithunsatheesh
i am trying to submit a xml request to a web service via Node.js using http.request.
我正在尝试使用 .js 通过 Node.js 向 Web 服务提交 xml 请求http.request。
Here is my code. My issue is that instead of data=1i want to post xml to the service.
这是我的代码。我的问题是,data=1我不想将 xml 发布到服务。
http.request({
host: 'service.x.yyy.x',
port: 80,
path: "/a.asmx?data=1",
method: 'POST'
}, function(resp) {
console.log(resp.statusCode);
if(resp.statusCode) {
resp.on('data', function (chunk) {
console.log(chunk);
str += chunk;
});
resp.on('end', function (chunk) {
console.log(str);
});
}
}).end();
Ho to do this?
何做这个?
采纳答案by Andrey Sidorov
http.requestreturns ClientRequestobject which is also a writable stream.
Instead of .end()do end(xmlbody)or .write(xmlbody).end()
http.request返回ClientRequest对象,它也是一个可写的流。而不是.end()做end(xmlbody)或.write(xmlbody).end()
回答by mithunsatheesh
Actually the link given by Andrey Sidorovhelped to get it working. This works.
实际上,安德烈·西多罗夫( Andrey Sidorov)提供的链接有助于使其正常工作。这有效。
var body = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'+
'<soap12:Body>......</soap12:Body></soap12:Envelope>';
var postRequest = {
host: "service.x.yyy.xa.asmx",
path: "/a.asmx",
port: 80,
method: "POST",
headers: {
'Cookie': "cookie",
'Content-Type': 'text/xml',
'Content-Length': Buffer.byteLength(body)
}
};
var buffer = "";
var req = http.request( postRequest, function( res ) {
console.log( res.statusCode );
var buffer = "";
res.on( "data", function( data ) { buffer = buffer + data; } );
res.on( "end", function( data ) { console.log( buffer ); } );
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write( body );
req.end();

