Reputation: 97
I'm trying to get the post variables in a little service I wrote but cannot seem to get it out of the request variable in my app.post method. I believe it's some way that I'm processing the request. Are there additional steps I must take to process the request? I've also tried using express.bodyParser() but I got an error saying that this is deprecated. The following is my little node.js file:
var express = require('express');
var app = express();
app.use(express.json());
// posting method : curl -X POST http://localhost:8080/post-page -d name=ArrowKneeous
// to look at the req I found it better to start using:
// nohup node testPost.js > output.log &
app.post('/post-page',function(req,res){
var name= req.body.name;
//undefined
console.log('name is :' + name);
//object
console.log('req is: '+req);
//object
console.log('req.body is: ' +req.body);
//undefined
console.log('req.body.name is: '+req.body.name);
//undefined
console.log('req.params[0]: '+req.params[0]);
//undefined
console.log('req.query.name is: '+req.query.name);
//empty brackets
console.dir(req.body);
//huge
console.dir(req);
//got stuff is replied to the curl command
res.send('got stuff');
});
app.listen(8080);
Upvotes: 2
Views: 3572
Reputation: 161657
You have
app.use(express.json());
to process a JSON post, but are POSTing standard URL encoded form data.
-d name=ArrowKneeous
You either need to post JSON
-d '{"name": "ArrowKneeous"}' -H "Content-Type: application/json"
or you need to tell express to also accept URL encoded POST data.
app.use(express.urlencoded());
This applies to Express 3.x
. It should be almost the same with 4.x
, but you will need to load the body-parser
module instead:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// OR
app.use(bodyParser.urlencoded());
Upvotes: 3