Search code examples
node.jsreactjsexpressaxiosexpress-session

Express session not persisting between api calls from react front end


Before asking this, I did have a look at other similar questions, but none of them have been of help as of yet.

I have a react front-end using axios to make api calls to a node backend using express and express session. Once I enter login info on my front end, I send it to my backend where I set a session and return a response to the front end that I set in the localStorage to use for client side validation.

When I try to access a protected api endpoint - from the front end - after logging in, the session does not have any of the information I set in it and thus, gives me an error. However, if I try to login and access the protected endpoint from postman, it works perfectly fine.

Here is my express-session config:

router.use(session({
 secret: 'notGoingToWork',
 resave: false,
 saveUninitialized: true
}))

Here is the api call (after logging in) I am making through axios:

axios.get(`http://localhost:5000/users/personNotes/${JSON.parse(userData).email}`)
    .then(response => console.log(response);

I do not know what the issue is and would appreciate any help. Thank you in advance!


Solution

  • try using withCredentials

    axios(`http://localhost:5000/users/personNotes/${JSON.parse(userData).email}`, {
      method: "get",
      withCredentials: true
    })
    

    or

    axios.defaults.withCredentials = true