lord
lord

Reputation: 59

Getting undefined using app.post and req.body

I am getting undefined for my req.body.number. I looked at previous post about this but it is still not working for me. I just want the number that was entered to be seen on the next page.

node js

//Sending UDP message to TFTP server
//dgram modeule to create UDP socket
var express= require('express')
var fs= require('fs')
var util = require('util')
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.get('/', function(req, res) {
    var html = fs.readFileSync('index2.html');
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
});

app.post('/', function(req, res) {
    console.log(req.body.number);
});

app.listen(3000, "192.168.0.172");
console.log('Listening at 192.168.0.172:3000')

html

<html>
  <body>
    <h1>Reading in Value</h1>
    <form action="/" method="post" enctype='multipart/form-data'>
    <br/>
    <label>Enter a UDP command in hex</label>
    <br/><br/>
    <input type="number" name="number" id="number">
    <br/><br/>
    <input type="submit" value="Submit" name="submit">
    </form>
  </body>
</html>

Upvotes: 1

Views: 105

Answers (2)

ofer goli
ofer goli

Reputation: 91

Just change

<form action="/" method="post" enctype='multipart/form-data'>

to

<form action="/" method="post" enctype='application/x-www-form-urlencoded'>

enjoy :)

Upvotes: 0

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

You are using enctype='multipart/form-data' in your form which is causing the problem.

Currently, body-parserdoesn't support multipart/form-data.Hence, req.body is undefined.

So, better to change it to application/x-www-form-urlencoded, if you don't have to upload file in that form.

Upvotes: 2

Related Questions