Reputation: 3415
I have a centOS server running a node.js http server (see code below) I'm trying to pass json from the command line: using
curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my","val3":"world"}' localhost:3000/app1/webServ1
Here is the code for node.js:
var http = require('http'),
express = require('express'),
path = require('path'),
lower = require('./lower.js');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res)
{
res.send('<html><body><h1>Hello World</h1></body></html>');
});
app.post('/:appName?/:webServ?', function (req,res) {
var appName = String(req.params.appName);
var category = String(req.params.category);
var webServ = String(req.params.webServ);
if ( (appName == 'app1') && (webServ == 'webServ1') )
{
console.log("in webserv1 post");
var address = req.body;
console.log("Got request: " + JSON.stringify(address));
console.log(address);
console.log(address.val1);
console.log(address.val2);
console.log(address.val3);
res.end();
}
});
Why do I keep getting the following error when I execute the CURL command stated above:
Got request: undefined
undefined
undefined
TypeError: Cannot read property 'val1' of undefined
Upvotes: 1
Views: 3989
Reputation: 25882
Two things you have to fix in your problem
1) Express doesn't parse request body by default. You'll have to use middle-wares for that.
require body-parser
var bodyParser = require('body-parser');
add these lines after or before your app.use line
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
If you are getting some warning of deprecated urlencoded
try this
app.use(bodyParser.urlencoded({
extended: true
}));
2) In your CURL request you haven't specified the Content-Type
attribute in your -H
option
should be like following
curl -X POST -H "Content-Type:application/json" -d '{"val1":"hello","val2":"my","val3":"world"}' localhost:3000/app1/webServ1
Upvotes: 3