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.