Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

nodejs - req.body is undefined

nodejs - req.body is undefined

Problem

I want to post some data to Server. The problem is that, it seems the server cannot receive the data.

So my post data is like this:

name=hello&email=there&message=sometext

and my server code is like this:

var url  = require('url'),
    express = require('express'),
    http=require('http'),
    path = require('path'),
    nodemailer = require('nodemailer');

var app = express();
var server = http.createServer(app);


app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));


app.get('/', function(req, res){
    res.render('home');
});

app.use(express.bodyParser());

app.post('/', function(req, response){

    console.log(req.body);
    // console.log(request.body.name);

});

server.listen(4000);
console.log('server running ' + 'now ' + Date.now());

when the console.log(reg.body) run, the terminal output is "undefined"

Problem courtesy of: Angry Kiwi

Solution

move app.use(express.bodyParser())); ahead of app.use(express.static(path.join(__dirname, 'public')));

Solution courtesy of: angry kiwi

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

nodejs - req.body is undefined

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×