My front (no Framwork) and back(nodejs with express) are independant
I have a lot of trouble to get the connect.sid cookie from express-session.
With the following configuration, I am able to make it work on Chrome.
But with Microsoft Edge or IE10, connect.sid cookie is blocked by navigator and never send back with other query.
Back nodejs example of my code
index.js
const express = require('express');
const cors = require('cors');
const router = require('./app/routers/index');
const session = require('./app/middleware/sessionMiddleware');
app.set("trust proxy", 1);
app.use((req,res,next)=>{
res.header('Access-Control-Allow-Credentials', 'true'),
next()
});
const corsOptions = {
credentials:true,
origin:['http://localhost:5500','http://127.0.0.1:5500']
}
app.use(cors(corsOptions));
app.use(session());
app.use(router);
const PORT = process.env.PORT || 3000;
app.listen(PORT,()=>{
console.log(`http://localhost:3000`)
});
express-session middleware
let cookie;
if(process.env.SESSION_MINUTES){
cookie = {
maxAge: process.env.SESSION_MINUTES * 60 * 1000,
sameSite:'lax',
}
}
const sessionMiddleware = ()=>{
return session({
saveUninitialized:true,
resave:true,
secret:process.env.SESSION_SECRET ?? 'hdlfdfMDFDFD5666674123ddkfkjfkjfMFDLKF@df',
cookie :cookie
});
}
module.exports = sessionMiddleware;
loginAction.controller
loginAction :async (req, res,next)=>{
try{
//find user in database
const user = findUserInDatabase();
if(!user){
res.status(422).json({
message:'error in login or password'
});
}
const { id, login } = user;
//user session
req.session.user = {
'id':id
};
res.status(200).json({
'authorize':true,
'message':'Welcome '+ login,
});
}
catch(error){
console.log(error)
}
};
front example
login.js (Fecth Parameter)
const setting = {
method: 'post',
credentials:'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body : JSON.stringify(dataLogin)
}
const response = await fetch(urlPath , setting);
thanks in advance for your help and reply
Cyrille