Sorry if this is a remedial question, or an obvious error, but this is my first Node project.
Essencailly what I need to do is get a line of text that a user will input into a form on the front end. Unfortunately no matter what I do the result logs 'undefined'. I'm at a loss. I'll post the full code below, but the section that giving me trouble is:
app.get('/test', function(req, res){
res.render('test');
});
app.post('/test',function(req,res){
console.log(req.body);
});
the '/test' route is just temporary to test getting the form response (if for some reason that wasn't obvious).
My full HTML file looks like this:
<!DOCTYPE HTML>
<head></head>
<body>
<form id="myform" action="/test" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="name" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
Any thoughts / help would be greatly appreciated.
Here is the full app.js file
var app = require('express')();
var http = require('http').Server(app);
var exphbs = require('express-handlebars');
var twitter = require('./twitter.js');
var hue = require("./hue_control.js");
//Variable that control Twitter Calls
var api = 'statuses/filter';
var params = {slug:'test', owner_screen_name: 'REDACTED', skip_status: true};
var values = {};
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
hue.activate();
twitter.tweetStream(api, params, values);
app.get('/test', function(req, res){
res.render('test');
});
app.post('/test',function(req,res){
console.log(req.body); //you will get your data in this as object.
console.log(req.is('json'));
});
app.get('/', function(req, res){
res.render('tweets');
});
app.get('/tweets', function(req, res){
res.render('home', {
profileImg: values.profileImg,
userName: values.userName,
screenName: values.screenName,
text: values.text,
timeStamp: values.timeStamp,
tweetScore: values.tweetScore
});
});
//app.get('/tweets', function(req, res)
http.listen(3000, function(){
console.log('listening on *:3000');
});
I think you are missing the bodyParser middleware in your express application which is why req.body is undefined.
If you are using Express 3.x, simply use the following line. BodyParser used to come bundled with versions prior to Express 4.0
app.use(express.bodyParser());
If you are using Express 4.x, You would need to require the body-parser module explicitly
var bodyParser = require('body-parser');
and then use it in your app
app.use(bodyParser());
Rest of your code seems fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With