Posting form data with Nodejs and body-parser
I've tried multiple times online already and I keep getting undefined for my data and console.log (JSON.stringify (req.body)) returns nothing either. So I am wrong somewhere ...
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Chat</title>
</head>
<body>
<form action="/" method="post">
<button>Close</button><br/><br/>
<label for="username">Your Name: *</label><br/>
<input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
<!-- <label for="email">Email: *</label><br/>
<input id="email" value="" name="email_address" autocomplete="off" required="required" /><br/> -->
<label for="phone">Phone:</label><br/>
<input id="phone" value="" name="phone" autocomplete="off" /><br/>
<label for="question">Question: </label><br/>
<textarea id="question" name="question">
</textarea required="required"><br/><br/>
<button type="submit">Chat</button>
</form>
</body>
</html>
JS:
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
+3
source to share
2 answers
Try adding the Urlencoded parameter :
var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');
// Add this line below
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
+3
source to share
Try using the express-fileupload package you can get in the req.body
var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')
app.use(fileUpload());
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
+1
source to share