1

I can access the session object data when using post method but session object data is null when using get method.How can i access session object data using get method. I am using express-session.

Front-end Code

For POST method

axios.post(url,{params:data},{withCredentials: "true"})

For GET method

axios.get(url,{params:data},{withCredentials: "true"})

Back-end Code Middleware for both get and post requests.

router.use((req: Request, res: Response, next: NextFunction) => {
  console.log(req);
  if (req.session && req.session.username) next();
  else res.status(401).send("Unauthorized");
});

1 Answer 1

2

axios.get() only takes two arguments (not three). The first is the URL and the second is the options. You are passing the options in the third spot which axios.get() does not look at. Therefore, it never sees the withCredentials: true option and thus doesn't send the session cookie and thus your server doesn't know how to find the session.

So, change from this:

axios.get(url,{params:data},{withCredentials: "true"})

to this:

axios.get(url,{withCredentials: "true"})

Note, there is no data argument for axios.get() because a GET does not send a request body, only a POST or PUT send the body. See the doc here.


Note: This bites people regularly with axios. .post() and .get() need a different number of arguments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.