NikolaJov
NikolaJov

Reputation: 37

Not able to get cookie from Node to React

I created a simple login system where after certain user logs in the backend I set profile cookie with jwt token value

           res.cookie('profile',jwt_token,{
                secure : false,
                httpOnly : true
           });

In React frontend I am sending a get request to Node backend where I expect to get that jwt token

             const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});

This is my controller for getting a cookie

export const test = async (req,res) =>{
   try {
         const cookie = req.cookies.profile || "no cookie";
         res.json(cookie);
    } catch (error) {
         console.log(error.message);
         res.status(406).json({success:false});
    }
 };

When I try to get a cookie after logging in with Postman I get cookie value but when I try to get the cookie from React through axios i am getting 'no cookie'. I've also set app.use(cors()) in Node

Upvotes: 0

Views: 1537

Answers (2)

t3__rry
t3__rry

Reputation: 2849

You might need to install the cookie-parser middleware http://expressjs.com/en/resources/middleware/cookie-parser.html and then add it to your app:

const cookieParser = require('cookie-parser');

//...

app.use(cookieParser())

Upvotes: 0

dan webb
dan webb

Reputation: 646

Apparently a known Axios bug exists that can be solved like this. Just add this line of code and try again.

 axios.defaults.withCredentials = true;
 const { data } = await axios.get('http://localhost:2000/users/test', {withCredentials:true});

Upvotes: 4

Related Questions