Saturday, 3 June 2017

Node Js session does not persist only when I use post request

Hi all im having problem getting session variables when i use 'POST' as request method.

My code as follows:

index.js:

var express = require("express");
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var pagesRouter = require('./routes/router');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var sessions = require('client-sessions');
var cors = require('cors');

app.use( express.static( __dirname + '/static' ));
app.use(cookieParser('a secret'));
app.use(cookieSession({
  secret: 'a secret',
  resave: false,
  saveUninitialized: true,
  cookie: { path: '/', httpOnly: true, maxAge: 30 * 60 * 60 * 1000 },
  rolling: true}));
app.get('/selam', function(req,res){
  res.send(req.session.test);
});

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

app.use(pagesRouter);

app.listen(8080,function(){
  console.log("Live at Port 8080");
});

router.js

var express = require("express");
var router = express.Router();
var path = require('path');
var request = require('request');
var session = require('client-sessions');
var apiPath = "http://localhost:8070/api/";
var webPath = "http://localhost:8080";

router.get("/",function(req,res){
  res.sendFile(path.join(__dirname,'../static/views/index.html') );
});

router.post("/login", function(req,res){
  request.post(
      apiPath + "auth",
      { json: { email: req.body.email, password: req.body.password } },
      function (error, response, body) {
          if (!error && body.statusCode == 200) {
            req.session.userId = body.userId;
            req.session.token = body.token;
            req.session.save();
            console.log("session user: " + req.session.userId);
            res.send(body);
          }else{
            res.writeHead(301,
              {Location: webPath+"?loginError=true"}
            );
            res.end();
          }
      }
  );
});


router.get('/test', function(req,res){
  req.session.test1 = "hi all";
  res.end();
});

router.get('/test1', function(req,res){
  res.send(req.session.test1);
});
/*router.use(function (req,res,next) {
  console.log(req.session.userId);
  if(!req.session.userId){
    res.writeHead(302, {'Location': webPath + '/'});
    res.end();
  }
  else
    next();
});*/

module.exports = router;

index.html (part that posts login request)

      <div class="col-xs-12 col-sm-6">
        <h3 class="text-center">SIGN IN</h3>
        <br>
        <form class="form-horizontal" method="post" action="/login">
          <div class="form-group">
            <div class="col-lg-12">
              <input type="text" class="form-control" id="login-email" placeholder="Email" name="email">
            </div>
          </div>
          <div class="form-group">
            <div class="col-lg-12">
              <input type="password" class="form-control" id="login-password" placeholder="Password" name="password">
            </div>
          </div>
          <div class="text-right">
            <button type="submit" class="btn btn-default">sign in</button>
          </div>
        </form>
      </div>

the problem is that when I use post in that form and post it directly with form's submit button userId and token is not written in session.

To test it whether is it related to post method I created test and test1 methods. in this method everything works fine. Therefore I am thinking it is related to post.

Am I missing a step to accept session cookies for post requests?



via necilAlbayrak

No comments:

Post a Comment