I am writing a signup feature for an application using Node Js and Express js.
This is how I’ve written the form in inside a bootstrap modal views/partials/signUp.
<div class="modal fade" id="signUp" tabindex="-1">
....
<div class="modal-body">
<form class="form-signup" id="sign-up-form" action="/views/partials/signUp" method="post">
and this is my post request in server.js
app.post('/signup', function (req,res) {
const connection = require('./connection');
const { username, email, dob, password } = req.body;
const createdAt = new Date().toISOString().slice(0, 19).replace('T', ' ');
const query = `INSERT INTO user_details (user_name, email, date_of_birth, password, created_at) VALUES ('${username}', '${email}', '${dob}', '${password}', '${createdAt}')`;
connection.query(query, (err, results) => {
if (err) throw err;
res.send('Registration is complete.');
res.redirect('/');
});
});
However, req.body was empty / undefined??
Therefore, I realized that there’s something wrong with the way I write form or with how I write post request.
Here’s the routes structure.
Here is the full source for the modal signup page.
views/signUp.ejs
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#signUp">
Sign Up
</button>
<!-- Modal -->
<div class="modal fade" id="signUp" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Sign Up</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form class="form-signup" id="sign-up-form" action="/views/partials/signUp" method="post">
<div class="form-floating mb-3">
<input type="text" id="username" class="form-control" placeholder="Username" required autofocus="" />
<label for="username">Username</label>
</div>
<div class="form-floating">
<input type="password" id="password" class="form-control" placeholder="Password" required autofocus="" />
<label for="password">Password</label>
</div>
<div class="modal-footer">
<button class="btn btn-lg btn-primary btn-block" id="signup-submit" type="submit" value="Submit">Sign Up</button>
</div>
</form>
</div>
</div>
</div>
</div>
Please let me know if you need any further information.
Appreciate your helps!