Reputation: 93
I'm having trouble accessing data from a form. As far as I can tell the following should allow me to read the username and password from the HTML form but, it is not working as expected.
Any help is appreciated.
Handlebars form ...
<form method="POST" action="/login" enctype="application/x-www-form-urlencoded">
<table>
<tr>
<td><input name="username" type="text" placeholder="User name"
required autocomplete="username"/></td>
</tr>
<tr>
<td><input name="password" type="password" placeholder="Password"
required autocomplete="current-password"/></td>
</tr>
<tr>
<td><input type="submit" value="Ok"/></td>
</tr>
</table>
</form>
...
Express controller
...
app.post("/login", (req, res) => {
//Prepare login request
const email = req.query.username
const pass = req.query.password
//Send login request
request.post("http://localhost:3000/users/login?email=" + email + "&password=" +
pass, function (error, restResponse, body){
//Handle response
if(error){
return res.status(400).send(error)
}
const user = body.user
const token = body.token
console.log("User: " + user + " Token: " + token)
return res.render("admin/index")
})
})
...
Upvotes: 0
Views: 693
Reputation: 93
Thank you to @Jatin Mehrotra his solution solved my problem here's the quote: "you are not using body parser that is why you are getting undefined.use this app.use(express.urlencoded({ extended: false })) in your app.js – Jatin Mehrotra "
Upvotes: 0
Reputation: 859
You need to use req.body
instead of req.query to access email and password from form body since the content-type is form data.
Also, it is bad practice to send email and password as query params even if used within trusted sources. This is because it is a general practice to log all request and thus not a good approach to have essentials details within query which could be logged.
Upvotes: 1