0

I'm trying authenticate user with JWT token. here is token I'm sending from API

  const token = user.getJWToken();
    const options = {
        expires:new Date(
            // convert days into ms
            Date.now + process.env.COOKIE_EXPIRE * 24*60*60*1000
        ),
        httpOnly:true
    }

    res.status(statusCode).cookie("token",token,options).json({
        success:true,
        user,
        token
    });

and here is my app.js for backEnd

app.use(express.json());
app.use(cookieParser());
app.use(cors())

now when I'm loggin in Reactjs. no cookies are stored . in postman everything is working fine. it show cookies in postman. but when I using it in frontEnd . no cookies are stored

    api.post("/api/v2/users/login", {
        email: loginEmail,
        password: loginPassword
      },{headers:{'Content-Type':"application/json"}})
      .then((res) => {
        console.log(res.data);
        setloggedIn(true);
      })
      .catch((err) => {
        console.log(err.message);
      });
  };

and api is

const api = axios.create({
 baseURL: process.env.REACT_APP_API_BASE_URL ,
});

2 Answers2

1

I think

  1. your code res.status(statusCode).cookie("token",token,options).json({...}) may have resulted in malformed JSON as response, depending on how 'user' and 'token' is structured? they both suppose to be key:val pair in your scenario.
  2. on the frontend, you still try to add 'withCredentials: true' as part of option to your axio request. if you are not familiar with this option, you can see some related post here: https://stackoverflow.com/a/16209531
coder joe
  • 31
  • 3
1

I had same problem i was using custom publicRequest method to login i solve it by adding {withCredentials: true} as option to request.

smit agravat
  • 223
  • 2
  • 9
  • Because this does not seem to add any additional insight, I perceive this as "Thank you" for https://stackoverflow.com/a/71777327/7733418 If that is what you intended, please delete this and upvote the existing answer. Otherwise please [edit] to make more obvious what additional insight your post provides. Ideally according to [answer]. – Yunnosch Sep 25 '22 at 21:51