Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read properties of undefined (reading 'username')

hello i got this problem . And i still not find out my issue. thanks you for helping me
this is code of login.js

    var express = require('express');
var router = express.Router();
var db=require('../database');
/* GET users listing. */
router.get('/login', function(req, res, next) {
  res.render('login');
});

router.post('/login', function(req, res){
    var username = req.body.username;
    var password = req.body.password;

    var sql='SELECT * FROM users WHERE username =? AND password =?';
    db.query(sql, [username, password], function (err, data, fields) {
        if(err) throw err
        if(data.length>0){
            req.session.loggedinUser= true;
            req.session.username= username;
            res.redirect('/dashboard');
        }else{
            res.render('login',{alertMsg:"Your username or password is wrong"});
        }
    })

})

module.exports = router;

and this is my login page (

<!DOCTYPE html>
<html>
<head>  
</head>
<body>
<div class="login-form">
  <h3>Login Form</h3>
<p><%=(typeof alertMsg!='undefined')? alertMsg:''%></p>
<form method="post" action="/login">
      <input type="text" placeholder="Username" name="username" required">
      <input type="password" placeholder="Password" name="password" required">
       <button type="submit">Login Now</button>
       <a href="/register">New Registration</a>
  </div>
</form>
</div>

</body>
</html>

and when i enter username and password and click login button it get this error :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeError: Cannot read properties of undefined (reading ‘username’)

Image of the error . Click here

Im happy if you can help me

>Solution :

It seems that the issue is with accessing the ‘username’ property of the ‘req.body’ object, which is resulting in a TypeError.

You can try adding a middleware function to your ‘login.js’ file that parses the request body. You can do this by adding the following line at the top of your ‘login.js’ file:

router.use(express.urlencoded({ extended: true }));

This will enable you to access the ‘username’ and ‘password’ properties from the request body. Make sure to restart your server after making this change.

Hope this helps 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading