2

I'm testing my express JS server and website locally. The website is supposed to send HTTP requests to the express server with javascript, which so far is running fine, except my sessions do not save. I have spent hours on end testing multiple different things, followed a number of tutorials, and the session will still not save. I've tried with and without CORS. When I visit the url in my browser, the session works just fine, but on the page I'm developing, I just keep getting undefined for the session on the server.

Here is a minimum example of code that I've cut down to (from https://www.tutorialspoint.com/expressjs/expressjs_sessions.htm and the CORS stuff elsewhere ):

var express = require( 'express' );
var cookieParser = require( 'cookie-parser' );
var session = require( 'express-session' );

var app = express();

app.use(function( req, res, next ) 
{
    res.header( 'Access-Control-Allow-Origin', '*' );
    res.header( 'Access-Control-Allow-Credentials', true );
    res.header( 'Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE' );
    res.header( 'Access-Control-Allow-Headers', "Origin, X-Requested-With, Content-Type, Accept" );
    next();
});

app.use( cookieParser() );
app.use( session( { secret: 'ssshhhhh' } ) );

app.get( '/test', function( req, res, next )
{
   if( req.session.page_views )
   {
      req.session.page_views ++;
      res.send( "You visited this page " + req.session.page_views + " times" );
   } 
   else 
   {
      req.session.page_views = 1;
      res.send( "Welcome to this page for the first time!" );
   }

   console.log( "viewcount " + req.session.page_views );
});
app.listen( 4444 );

Here is my jquery request ( which I have also tried in ajax, with credentials, without, you name it ):

$.get( "http://localhost:4444/test", {}, 
    function( data )
    {
        alert( data );
    });

I have spent multiple days straight on this - any help will be much appreciated, thank you.

T. Elliott
  • 31
  • 5
  • 1
    I think you have to add in your frontend ajax call the ability to send the cookie in a CORS request. Using `$.ajax()` there is the option `xhrFields: { withCredentials: true }` that link you've used is exclusive for backend code - it omits the frontend part. See https://stackoverflow.com/questions/36824106/express-doesnt-set-a-cookie – Gonzalo.- Jul 31 '18 at 03:03
  • What do your logs show? Is it `viewcount undefined` or `viewcount 1`? – danroshko Jul 31 '18 at 03:54
  • What's the URL for the web page that this Ajax call is coming from. Is the web page also loaded from http://localhost:4444? If not, you probably have a CORS issue. – jfriend00 Jul 31 '18 at 04:09
  • Yes it was all on localhost:4444. However I have just realised that it works fine in Internet Explorer, but not Chrome, Firefox, or Edge. Any ideas? – T. Elliott Aug 01 '18 at 04:15

0 Answers0