Home > front end >  Receive Express session Id from React app
Receive Express session Id from React app

Time:03-17

I am learning Express.js, trying to create an api and connect it to React frontend. In express, I'm using express-session to create a session. For authentication, I use passport.js. Here is the part of my app.js file:

const session = require('express-session');
const mongoDbStore = require('connect-mongodb-session')(session);
const store = new mongoDbStore({
    uri: 'mongodb://localhost:27017/DB_NAME',
    collection: 'UserSessions'
});

const app = express();

app.use(cors())

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

const sessionConfig = {
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    store,
    cookie: {
        expires: Date.now()   1000 * 60 * 60 * 24 * 7,
        maxAge: 1000 * 60 * 60 * 24 * 7,
        httpOnly: true
    }
}

app.use(session(sessionConfig));

app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser())


app.listen(8080, () => {
    console.log('listening on port 8080')
});

My issue is that when I send a request to my backend from my React app, I don't receive session id as a cookie. On my frontend, I use axios, to send requests:

import axios from 'axios';

export default axios.create({
    baseURL: "http://localhost:8080/",
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

Why I don't receive a cookie from backend on my frontend and how can I fix this? Thank you!

CodePudding user response:

Because your cookie is a httpOnly cookie so in order to send the cookie you can do by fetch method:

const req = await fetch(URL,{
  method : "POST",
  credentials : "include", // to send HTTP only cookies
  headers: {
   "Contetnt-Type" : "application/json"
 },
 body : JSON.stringigy({name : "Bob"})
}):
const result = await req.json();

By axios you can also add withCredential properties:

axios.get(BASE_URL   '/todos', { withCredentials: true });

and also in backend consider this parametrs:

 const corsOptions = {
   optionsSuccessStatus: 200,
   credentials: true,
 }
 app.use(cors(corsOptions))
  • Related