axios not retrieving cookie

10,816

Solution 1

I figured out how to fix this. I used:

Server:

app.use(
  cors({
    credentials: true,
    origin: 'http://myapp.com',
  })
);

React:

export function loginUser({ email, password }) {
  axios.defaults.withCredentials = true;
  const request = axios
    .post(`${url}/api/login`, {
      email,
      password,
      withCredentials: true,
      headers: { crossDomain: true, 'Content-Type': 'application/json' },
    })
    .then(response => response.data);

  return {
    type: 'USER_LOGIN',
    payload: request,
  };
}

Solution 2

Try to use defaults axios.defaults.withCredentials = true

It's a known bug with axios

Share:
10,816
Matt
Author by

Matt

Full Stack Developer and Development Operations Manager with 4+ years of experience creating well designed and responsive web applications as well as leading a team of developers. I am proficient in mobile-first responsive design and test-driven development. I am proficient in Azure DevOps as well as using Azure Web Apps and Azure Databases. I have achieved my dreams of becoming a Full Stack Developer as well as a Development Operations Manger and I am looking to fulfill my next goal. Full Stack Developer and Project Manager aiming to leverage experience and dedication into your Developer role. I possess a B.S. in Information Technology.

Updated on June 04, 2022

Comments

  • Matt
    Matt almost 2 years

    Hey I am having an issue where when I am running the server and app locally there is no issue but when each is pushed to their respective servers the app does not return the cookie. Does anyone know how to get around this?

    server:

    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Credentials', true);
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept'
      );
      next();
    });
    

    react:

    const request = axios.post(`${url}/api/login`, {
          email,
          password,
          withCredentials: true,
          headers: { crossDomain: true, 'Content-Type': 'application/json' },
        })
        .then(response => response.data);
    
  • Matt
    Matt over 5 years
    Thank you but where would I put that? Within the request?
  • Vitaly Migunov
    Vitaly Migunov over 5 years
    Just put it before the request
  • David Ferreira
    David Ferreira about 5 years
    It works for me. Works even without the headers option.