Reputation: 11
Basically, this simple form submit does not return anything. Using postman, I can only get the request.body data, or undefined (console.log) / {} for the input name. On form submit nothing happens at all. I've read all the body-parser solutions, but it is my understanding that this now taken care of by express 4.
here is my form (home.ejs):
<form action="/" method="POST">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" id="name">
</div>
<button type="button" type="submit" class="btn btn-primary submit">Submit</button>
</form>
Here is my server code:
//Load packages
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.use(express.static('public'));
app.set("view engine", "ejs");
//SERVER
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
})
//render home page
app.get('/', function(req,res){
res.render("home");
});
//post request
app.post('/', function(req, res)
{var body = res.json(req.body)
var name = body.name;
console.log(name);
});
Upvotes: 1
Views: 2105
Reputation: 1722
You can use express.urlencoded
or bodyParser.urlencoded
both are same link
The thing you need to change here is there are two button type so add only one
<button type="submit" class="btn btn-primary submit">Submit</button>
and replace with this code
//post request
app.post('/', function(req, res){
var name = req.body.name
res.json(name);
//res.send(name);
console.log(name)
});
Upvotes: 0
Reputation: 130
run "npm i body-parser" in your CLI and import body-parser like
const bodyParser = require('body-parser')
and then use the middleware
app.use(bodyParser.urlencoded({ extended: true }));
also you should update the post request handler
//post request
app.post('/', function(req, res)
{var name = req.body.name;
console.log(name);
res.status(201).send();
});
Upvotes: 1