I have a big problem with Node.js and Express.
I want to use the body elements of my request but I dont know how to use the bodyParser() in my program; it's not just app.use()...
See for yourself:
requestServer = function(){
var express = require('express');
this.ex = express;
//this.app = require('express')();
this.app = express();
this.server = require('http').createServer(this.app);
this.io = require('socket.io').listen(this.server, {log: false});
this.socket = [];
this.app.post('/test/', this.testFunction.bind(this));
this.io.sockets.on('connection', this.socketConnection.bind(this));
this.app.use(express.bodyParser());
};
...
requestServer.prototype.positionChange = function(req, res){
console.log(req.body); // says its undefined???
console.log(req.body.name); // also undefined :(
};
...
var server = new requestServer();
server.listen(6667);
What am I doing wrong?
If you want to use nodejs, express and bodyParser i suggest you to make yourself clear about the method used for the request. Do you mean to use the get method or the post ? Remember to answer according to the utilization of the information you gain with the communication.
I suppose you want to use the post method because the body parser has been created for the post method, and the query for the get method.
---client side: just write a form element specifying it uses the post method. Give each input element a name.
<form method="POST" action="/readRequest">
<input type="text" name="email" hint="email" value="" size="40"/>
<inpnut type="submit" value="request" />
</form>
---node side : into the middleware you want to catch the /readRequest, read the values with the '.' operator on the request element
function (req, res, next){
console.log('Email received: '+req.body.email);
next();
}
BodyParser is no longer being used widely due to security exploits with it. It is now integrated in Express itself. Don't use it.
Should not this
var server = new requestServer();
server.listen(6667);
be this
var server = new requestServer();
server.app.listen(6667);
Since app is the express object, which is returned. Can you post the full code where positionChange is called.