I am new to node js & express. I was able to get my first Node JS form today and it is working as expected. So I wanted to recreate the same on Express, but for some reason I am programmatically failing at it. I am able to track the headers and the body down, but for some reason I am failing to understand why would Express rewrite the way body is being handled.
I am adding in my findings. Below is the code, this was generated via express command line tool. This is the app.js file, the method upload is looking for some data. I am not handling any file uploads at the moment, I am only looking for some text to come across.
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
/**custom stuff**/
app.post('/upload',function(req, res){
console.log(req.header('Content-Type'));
console.log(req.header('Host'));
console.log(req.header('User-Agent'));
console.log(req.body);
res.send("Hello the response is "+req.body.username);
});
/** end**/
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Now I make a curl call to the function.
curl -d '{"username":"myname"}' -H 'Content-Type: application/x-www-form-urlencoded' http://localhost:3000/upload
And these are the headers and the body.(headers end at line 3, body is on line 4)
application/x-www-form-urlencoded
localhost:3000
curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
{ '{"username":"myname"}': '' }
POST /upload 200 7ms - 36b
Now, I used Advanced Rest Client App for Google Chrome and below are the headers and the body.
application/x-www-form-urlencoded
localhost:3000
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
{ username: 'myname from adv rest client app' }
POST /upload 200 5ms - 58b
So, the one thing that is confusing me is why would the body for the request made by the rest client app be well formed and intact while the body from my request is distorted. Can anyone help me out with this here.
Thank you