Ank i zle
Ank i zle

Reputation: 2357

req.body.username being undefined

in express js, i am using body parser to get the username. when i try to get the username, it returns undefined. Can anyone help me?

app.use(session({
 cookieName: 'session',
 secret: "Shh_It's_a_secret",
 duration: 100000 * 100000
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/home', (req, res) => {
if(req.body.username){
 res.send('Invalid Username, Press The Back Button To Try Again');
} else if (!req.body.username) {
  app.use(express.static(__dirname + '/NerdFestProjectHomepage.html'));
  res.sendfile('NerdFestProjectHomepage.html');
  console.log(req.body.username);
}
})

When i try to get req.body.username, it returns undefined.

Upvotes: 1

Views: 196

Answers (1)

Atish Shakya
Atish Shakya

Reputation: 561

It's a GET request. In express it is not possible to send "body" using GET request.

Change GET to POST request :

app.post('/home', cb );

And in view use :

<form action="/home" method="POST"></form>

Upvotes: 5

Related Questions