LearnCode Master
LearnCode Master

Reputation: 552

request body undefined in node express

In node express when I try to access the post value from the form it shows request body undefined error. Here is my code,

http.createServer(function(req, res) {
    var hostname = req.headers.host.split(":")[0];
    var pathname = url.parse(req.url).pathname;

  if (pathname==="/login" && req.method ==="POST") {
  console.log("request Header==>" + req.body.username );

}).listen(9000, function() {
    console.log('http://localhost:9000');
});

Please any one help me to find why the request body shows undefined.

Upvotes: 2

Views: 2308

Answers (2)

paolord
paolord

Reputation: 399

If you're not using express for the web server and just plain http. Use the body module.

Upvotes: 0

Alexey B.
Alexey B.

Reputation: 12033

Enable body-parser middleware first

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

Upvotes: 1

Related Questions