宁静相当于curl命令

时间:2016-10-03 06:18:28

标签: xml node.js rest curl

curl -X POST -d @test.XML https://example.com/example

上述curl命令的其余部分是什么,其中test.XML是XML文件。 或者我们如何在nodejs中复制此请求?

1 个答案:

答案 0 :(得分:0)

答案基于this thread

var xmlbody;

function processFile() {

    var postReq = {
        host: 'example.com',
        port: 443,
        path: '/example',
        method: 'POST',
        headers: {
            'Cookie': 'cookie',
            'Content-Type': 'text/xml',
            'Content-Length': Buffer.byteLength(xmlbody)
        }
    };

    var req = require('http').request(postReq, function(resp) {
        var str;
        if(resp.statusCode) {
            resp.on('data', function (chunk) { str +=  chunk; });
            resp.on('end', function (chunk) {});                   
        }
    });

    req.write(xmlbody);
    req.end(); 
}

require('fs').readFile('@test.XML', function read(err, data) {
    xmlbody = data;
    processFile();
});

另外,下面是我的服务器端测试代码。

var express = require('express');
var app = express();
var xmlparser = require('express-xml-bodyparser');
app.use(xmlparser());
app.post('/', function(req, res){
    console.log(req.body);
    return res.end();
});    
app.listen(/* port */)

服务器端的输出来自w3c

{ note: 
   { to: [ 'Tove' ],
     from: [ 'Jani' ],
     heading: [ 'Reminder' ],
     body: [ 'Don\'t forget me this weekend!' ] } }