Tuesday 24 May 2016

javascript - 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





  • NodeJS v6.5.0

  • ExpressJS v3.14.0

  • CURL v7.22.0



==================
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

Answer




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;
...
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...