0
votes

I've set a simple NodeJS web-app, the basic functionally is to login, and then based on session data the app pull some data from the MySql. that is working (Link).

once I write the client-side in react the session data is not stored (therefore app not working) any ideas? are there any specific react requirements for react to enable sessions?

note: in react after the page redirects (successfully) to menu.html I'm expecting the req.session to have an auth property (=true) but when I log the session data it is empty. therefore I assume the session data is not stored.

Login.js

const express = require('express');
const con = require('../config/mysqlCon.js');
const session = require('express-session');
const router = express.Router();

app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true,
}))

router.post('/',approveUserPassword, function(req, res){

  if(req.session.auth){
    let url = '/menu.html';
    res.redirect(url);

  }else{
    req.session.auth = false;
    let url = '/index.html';
    res.redirect(url);

  }
});


function approveUserPassword(req, res, next) {

  let email = req.body.email;
  let psw = req.body.psw;
  let query = "SELECT id FROM Users " +
              "WHERE email= '" + email + "' AND " +
              "password='" + psw + "'";

  con.query(query, function (err, result, fields) {
    if (err) throw err;

    if(result.length > 0){
      req.session.auth = true;
      req.session.rest_id = result[0].id;
      req.session.save();

    }else{
      req.session.auth = false;
    }

    next();
  });
}

just noted that 2 sessions are created, not sure why. Node js listen on port 8080...

login

Time:1509727252952 id:j1KIe081XzRhWKKKM7z5Jjv1N6Cderee Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } }

menu

Time:1509727252955 id:j1KIe081XzRhWKKKM7z5Jjv1N6Cderee Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } } Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, auth: true, rest_id: 100 }

login

Time:1509727253124 id:rqCBY1fnH5WpS9M6Brp6RZokxMWzf0Pk Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } }

menu

Time:1509727253124 id:rqCBY1fnH5WpS9M6Brp6RZokxMWzf0Pk Session { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true } } rqCBY1fnH5WpS9M6Brp6RZokxMWzf0Pk

1
Just noted that there are 2 sessions created, still not sure why:Yaniv Peretz

1 Answers

0
votes

Express router create a new session not wanted

I guess it is some issue when creating the ajax request:

fetch('/api/myroute', {
    credentials: 'same-origin' // This is the line you are missing 
}).then(response => response.json())
.then(json => {
    dispatch({
        type: types.MY_ACTION, forms: json, receivedAt: Date.now()
    })
})