Katie
Katie

Reputation: 48308

How to retrieve POST data in NodeJS that was passed using CURL?

I am trying to pass some parameters to my localhost (which is using nodejs) with a CURL command, but my localhost isn't reading them correctly.

I am doing my POST request to my localhost like this:

curl --data "db_name=auto&old_db=Lab.tar.gz&new_db=627999E00_10.tgz" 
     --noproxy localhost 
     -H "Accept: text/plain" 
     -H "Content-Type: text/plain" 
     -X POST http://localhost:8084/auto

And I try to retrieve my data params with node like this:

app.post('/auto',function(req,res){
    var db_name=req.body.db_name; //undefined
    var old_db=req.body.old_db; //undefined
    var new_db=req.body.new_db; //undefined
    ...
});

But db_name,old_db,new_db are all always undefined.

Also, req.body is an empty object {}

And req.url is just /auto

How to I retrieve the parameters that I passed with my curl program in node?

================== Versions

================== Updates

My ExpressJs configuration is the following:

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(app.router);
app.use(express.static(_path.join(__dirname, '..', 'Client')));

Also I tried some other curl variations:

curl --noproxy localhost 
     -H "Accept: text/plain" 
     -H "Content-Type: application/json" 
     -X POST 
     -d "{'db_name':'auto','old_db':'Lab.tar.gz','new_db':'627999E00_10.tgz'}" 
     http://localhost:8084/auto

Upvotes: 2

Views: 2386

Answers (2)

Katie
Katie

Reputation: 48308

Finally got it to work with the help from @J.Chen and @hanshenrik !

If I change the format of the --data in my CURL request to be a JSON object (like {'key':'value',...}) instead of a string (key=value&...),

AND if I remove the -H "Accept: text/plain" -H "Content-Type: application/json" from the CURL request,

Then my nodeJS Application finally sees the parameters in req.body.

So my final code is:

curl --noproxy localhost 
     -X POST 
     -d "{'db_name':'auto','old_db':'Lab.tar.gz','new_db':'627999E00_10.tgz'}" 
     http://localhost:8084/auto

And my NodeJS code is:

app.post('/auto',function(req,res){
    var parseMe = Object.keys(req.body)[0];
    var parsedParams = JSON.parse(parseMe);

    var db_name=parsedParams.db_name; 
    var old_db=parsedParams.old_db; 
    var new_db=parsedParams.new_db; 
    ...
});

Upvotes: 4

pizzarob
pizzarob

Reputation: 12059

Try adding the json body parser middleware

const bodyParser = require('body-parser');
app.use(bodyParser.json());

Upvotes: 1

Related Questions