var express = require('express');
var app = express();
app.use(express.cookieParser('keyboard 123'));
app.get('/', function(req, res){
res.sendfile('./login.html');
});
app.use(express.session());
app.post('/login', function(req, res){
console.log(req.body);
if (req.session.user) {
req.session.user=req.body.username;
} else {
req.session.user="test";
}
});
<form id="myform" action="/login" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="username" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
I am trying to understand and use express node js .
Here I have a form which does post.
My understanding is that :
the first time there is no cookie(session) available.
so, when we get a request : req.session.user will be empty.
so when we send 200 OK. this req.session.user cookie wil be created and stored in the local browser.? and subsequently in all the req this req.session object will be send is that correct?
Issue now is : I always get req.body.username as undefined.
I have the same user name defined in the login page.
I have tried console.log(req.body) and it is always undefined.
if I have no session, the body part works.
can you clarify me if I am understanding is correct and what is the issue in this code. I am having really issues understandging the concept of session and how to use it in express frame work
It seems like you are confusing the request and response. If you post a larger code excerpt, we can give more detailed help, but here’s my take on your misunderstanding.
req.session.useris set. If so, the user is already logged in but logging in again, which is not a usual case, but you could do something likeres.send('You are already logged in as ' + req.session.user);req.session.useris not set, the user is logging in. Normally you would confirm the user knows the right password, but for your little test app you would just do as you havereq.session.user = req.body.usernameand respond with `res.send(‘You have been logged in as ‘ + req.session.user); for example.Also just make sure you have the cookieParser, session, and bodyParser middlewares configured properly in your application.