The server services(localhost/8000) successfuly stored the jwt token in cookies and send response cookies to client services. The cookies successfully stored on client services(localhost/3000) but when i want to retrive it,it shows undefined.i also include the cookie-parser package but its still showing undefined.
server services:
export const saveprofile = async (req, res) => {
try {
const profile = await new Profile(req.body);
if (req.body.password === req.body.cpassword) {
const token = await profile.generateAuthToken();
res.cookie('token', token, { expires: new Date(Date.now() + 9999999), httpOnly: true })
profile.save();
res.status(200).json('profile saved !!');
}
} catch (error) {
req.status(500).json(error);
}
}
Now when i want to console the token stored in cookies through auth function,it shows undefined.
Auth function (middleware)
import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';
import Cookies from 'js-cookie';
const auth = async (req, res, next) => {
try {
const token = req.cookies.jwt;
console.log("The token is", token) //it shows undefined
const verifyuser = jwt.verify(token, "mynameismohitkumarfromnationalinstituteoftechnologyagartala");
const user = await profile.findOne({ _id: verifyuser._id });
console.log(verifyuser);
console.log(user);
next();
} catch (error) {
res.status(401).json(error);
}
}
export default auth;
Authentication Routes:
router.get('/post/:id', auth, getpost);
I guess the issue here is naming
You name the cookie "token" on the server-service and save it as such. But then in the auth-middleware you try to receive the "jwt"-cookie
As a side note:
profile saved !! is not valid JSON