I am having problem that I cannot find the cookies after sending them to the frontend.
//server js
const express = require('express');
const app = express()
const connect = require('./backend/db/dbConnect')
const cors = require('cors');
const cookieParser = require('cookie-parser');
connect()
app.use(cors({
origin: 'http://localhost:5173',
credentials: "include",
}));
app.use(express.json());
app.use(cookieParser());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:5173');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use('/api/v1', require('./backend/routes/route') )
app.listen(3000, ()=>{console.log('server on http://localhost:3000');})
//route js
const {refreshToken} = require('../controller/userController');
router.route('/refreshtoken').post(refreshToken);
controller.js
// @ for login user
const loginUser = asyncHandler(async (req, res) => {
console.log(req.body);
try {
const { userEmail, password } = req.body;
const foundUser = await userScema.findOne({ email: userEmail });
if (!foundUser) return res.status(400).json({ success: false, message: "Useremail or password is incorrect." });
const isPasswordMatch = await bcrypt.compare(password, foundUser.password);
if (!isPasswordMatch) return res.status(400).json({ success: false, message: "Useremail or password is incorrect." });
const accessToken = jwt.sign({ userId: foundUser._id }, JWT_SECRET_KEY, { expiresIn: '15m' });
const refreshToken = jwt.sign({ userId: foundUser._id }, JWT_REFRESH_KEY, { expiresIn: '7d' });
res.cookie('refreshToken', refreshToken); // i cannot find this cookis
res.cookie("hello","world") // also this cookies
res.status(201).json({ success: true, accessToken: accessToken, });
console.log("Set-Cookie Headers: ", res.getHeaders()['set-cookie']);
} catch (err) {
res.status(400).json({ success: false, error: "Server error." });
}
});
const refreshToken = (req, res) => {
const { refreshToken } = req.cookies;
console.log(req);
if (!refreshToken) return res.status(401).json({ error: "Unauthorized" });
jwt.verify(refreshToken, JWT_REFRESH_KEY, (err, user) => {
if (err) return res.status(403).json({success:false, error: "Invalid refresh token" });
const newAccessToken = jwt.sign({ userId: user.userId }, JWT_SECRET_KEY, { expiresIn: '15m' });
res.json({ accessToken: newAccessToken });
});
};
this is the log of when logging in
// @logs on console
# [nodemon] starting `node server.js`
# server on http://localhost:3000
# enstablish db connection on 127.0.0.1
# { userEmail: '[email protected]', password: 'dave' }
# Set-Cookie Headers: [ 'refreshToken=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NmY4MDEzOGRjZGY1NWM2ZTUwODI2MTIiLCJpYXQiOjE3Mjc1MzU4OTQsImV4cCI6MTcyODE0MDY5NH0.5rOiG0JrKPnD8rzXf8M77PjPtkHJ41hB2Rif_L-aZhE; Path=/', 'hello=world; Path=/']
this is the console log when try to go to the route “/refreshtoken” from frontend
# cookies: [Object: null prototype] {},
# signedCookies: [Object: null prototype] {},
# route: Route {
# path: '/refreshtoken',
# stack: [ [Layer] ],
# methods: { post: true }
# },
first i am trying to get cookies in the front end and it is not genarating, i think somthing is worng in server, the cookie is sending but not getting,Can anyone help me please!!!