angry kiwi
angry kiwi

Reputation: 11485

nodejs - req.body is undefined

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"

Upvotes: 4

Views: 4015

Answers (3)

Johan Sené
Johan Sené

Reputation: 1

There is no need to install body-parser. The current version of Express has a built-in body parser.
If installed, you can use:

app.use(express.json())

Upvotes: 0

angry kiwi
angry kiwi

Reputation: 11485

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

Upvotes: 1

Suleman Mirza
Suleman Mirza

Reputation: 925

All query strings output are parsed by default by app.use(express.bodyParser());.. simple solution to your problem is try logging req.query , something like

console.log(req.query);

Upvotes: 4

Related Questions