4

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"

angry kiwi
  • 10,730
  • 26
  • 115
  • 161
  • `name=hello&email=there&message=sometext` seems `GET` data to me. You should send them in `form` or `params` in **AJAX POST** – jwchang Nov 18 '12 at 12:52
  • it was ajax post, have a look at this screenshot https://www.dropbox.com/s/joacijxke8pyfox/Screen%20Shot%202012-11-18%20at%208.18.25%20PM.png – angry kiwi Nov 18 '12 at 13:19
  • Which version of express are you using? You could also try to log the entire `req` object, that will most likely show enough information that you can answer your question yourself;) – Tiddo Nov 18 '12 at 13:36
  • 5
    Try to move `app.use(express.bodyParser()));` ahead of `app.use(express.static(path.join(__dirname, 'public')));` – jwchang Nov 18 '12 at 13:37
  • inspiredJW, you are right, change the order of the code will work. Why don't u make it as an answer? – angry kiwi Nov 18 '12 at 13:40

3 Answers3

4

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);
Suleman Mirza
  • 905
  • 1
  • 12
  • 22
  • Please mark it as an answer if it solves your problem. even if it is an outdated question. – Suleman Mirza Aug 29 '13 at 22:09
  • Used the way you said in your answer has been deprecated in Express 4. I found this answer helpful, but the proper way to use `bodyParser` is here: http://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4 – Kevin Ghadyani Jan 02 '16 at 11:40
1

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

angry kiwi
  • 10,730
  • 26
  • 115
  • 161
0

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())