I have made login/signup page and the corresponding routes using NodeJS. The problem i am facing is that on clicking submit button, signup route is calling but the data is not transferring in request body.
this error message is showing
{"message":"User validation failed: username: Path
username
is required., password: Pathpassword
is required."},
I have also run this route on postman. there everything is functioning properly. data is properly store in database.
This is the signup form.
<div id="signup-form">
<h2>Signup</h2>
<form method="post" action="/signup">
<div class="form-floating mb-3">
<input type="text" class="form-control" for="username">
<label for="username">Username</label>
</div>
<div class="form-floating">
<input type="password" class="form-control" for="password">
<label for="password">Password</label>
</div>
<button type="submit" class="btn btn-primary" onclick="showLoginForm()">Signup</button>
</form>
<div class="instead-button">
<button class="btn btn-primary" onclick="showLoginForm()">Login instead</button>
</div>
</div>
and this is backend code
app.post('/signup', async (req, res) => {
try {
console.log('inside');
const { username, password } = req.body;
const user = await User.create({ username, password });
res.status(201);
} catch (error) {
res.status(400).json({ message: error.message });
}
});
2
Answers
There’s small mistake you have done in your HTML code.
When you do the form submission, the body will be taken by the
name
attributes of input fields.But
You have added
for
attribute toinput
field. Andname
attribute is missing.Hence the issue is.
Change your code to this :
This will solve the issue.
you forgot define name attribute in html form input element