Home > front end >  req.cookies returns [Object: null prototype] {} in only Post request
req.cookies returns [Object: null prototype] {} in only Post request

Time:11-26

I'm trying to implement authentication with jwt in nodejs and frontend reactjs. I send the accessToken in the response when user login. And them I test the cookies with two end points. First end point is Get method and the second is Post method. After calling the first end point with GET method server response the cookie well but the second end point with Post method response 'Object: null prototype] {}'.

Creating Secure Cookie with refresh token

res.cookie('jwt', refreshToken, { 
      httpOnly: true, 
      secure: true, 
      sameSite: 'None', 
      maxAge: 24 * 60 * 60 * 1000
     })

frontend code for GET method

const testCookiesGetMethod = (e) => {
        e.preventDefault();
        axios.get('auth/test',{ 
            withCredentials: true,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
        });
    }

Server side code for GET Request

export const testGet = (req, res) => {
    console.log(req.cookies);
}

Output for GET Method

{
jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InllbGxvdyIsImlhdCI6MTY2OTM1NjYxMiwiZXhwIjoxNjY5NDQzMDEyfQ.5cibdr1bboyNf3p4fUXkp4nVO3SE2lPi_h5FUBrzqjE'
}

frontend code for POST method

const testCookiesPostMethod = (e) => {
        e.preventDefault();
        axios.post('auth/test',{ 
            withCredentials: true,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
        });
    }

server side code for POST request

export const testPost = (req, res) => {
    console.log(req.cookies);
}

output for POST Method

[Object: null prototype] {}

CodePudding user response:

Because when you are using the post Axios shorthand method the second argument has to be the data you want to send to the server, and in the third argument you pass the options object:

const testCookiesPostMethod = (e) => {
        e.preventDefault();
        axios.post('auth/test', 
            {}, //here a data to be sent
            { 
            withCredentials: true,
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
        });
    }
  • Related