thisisme_22 thisisme_22 - 2 months ago 15
reST (reStructuredText) Question

restful equivalent of curl command

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


What is the restful equivalent of the above curl command, where test.XML is the XML file.
Or How could we replicate this request in nodejs?

Answer

The answer is based on 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();
});

Also, below is my server side test code.

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 */)

Example output on server side from w3c:

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