Saturday, 20 May 2017

how to read the -d parameter in a post route (curl http)

I am trying to get the data from my json file into the body to accomplish a POST request to my api.. Please how can i achieve that?.. I know i need this url:

curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' https://be-task0-
  giresse19.c9users.io/api/create

Where the -d is the json body.. my question is how can i get this in php for instance we achieve it by ($requestBody = file_get_contents("php://input") )how can i do that from node.js app from my code which is below.. thank you!: Here is a snippet of the code:

app.post("/api/create", function(req, res) {
    var body = '';
    req.on('data', function(data) {
        body += data;
        // If someone is trying to nuke RAM, nuke the request
        // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
        if (body.length > 1e6) {
            req.connection.destroy();
        }
    });
    req.on('end', function() {


        process_request(body);
    });
    function process_request(body) {
        // Continue with parsing json string in body and inserting organisation
        // json string is stored in the body variable
        var org = JSON.parse(body);
        insert_organisation(org, 0);
        res.end('INSERTED');
    }

By the way i already have the header defined(-H), i.e in :

res.setHeader('Content-Type', 'application/json');

all i need is how to access the id into the body.I have a file called orgs.json with content:

var body= {
        "org_name": "Paradise Island",
        "daughters": [{
            "org_name": "Banana tree",
            "daughters": [{
                "org_name": "Yellow Banana"
            }, {
                "org_name": "Brown Banana"
            }, {
                "org_name": "Black Banana"
            }]
        }, {
            "org_name": "Big banana tree",
            "daughters": [{
                "org_name": "Yellow Banana"
            }, {
                "org_name": "Brown Banana"
            }, {
                "org_name": "Green Banana"
            }, {
                "org_name": "Black Banana",
                "daughters": [{
                    "org_name": "Phoneutria Spider"
                }]
            }]
        }]
    };



via giresse

No comments:

Post a Comment