使用app.post和req.body获取undefined

我越来越undec为我的req.body.number。 我看了以前的这篇文章,但它仍然不适合我。 我只是想要input的号码在下一页看到。

节点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> 

您正在使用enctype='multipart/form-data'在您的forms导致问题。

目前, body-parser不支持multipart/form-data 。因此, req.body是未定义的。

因此,最好将其更改为application/x-www-form-urlencoded ,如果不必以该forms上传文件。

只是改变

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