How to fetch cookies value from client service to server service in react js? The cookie successfully stored on the clent side but when i am trying console from server side it is showing undefined .
please help me !!
index.js (server side):
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
const app = express();
import cookieParser from "cookie-parser";
import connection from "./database/db.js";
import Router from "./routes/route.js";
import auth from "./middleware/auth.js";
const corsOptions = {
origin: true, //included origin as true
credentials: true, //included credentials as true
};
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(bodyParser.json({ extended: true }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/', Router);
app.use(express.json());
const PORT = 8000;
app.listen(PORT, () => {
console.log(`server is running successfully at ${PORT}`);
})
connection();
Auth.js (Authentication middleware(server side)):
import jwt from 'jsonwebtoken';
import post from '../schema/post-schema.js'
import profile from '../schema/profile-schema.js';
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;
Have a look at cookie options if the cookie is HttpOnly then you cant read the cookie from the client-side.