0

in my server side (nodejs )

const passport = (res, user, statusCode) => {
    const jwt_ = jwt.sign({ id: user._id }, process.env.JWTSECRET, {
        expiresIn: process.env.JWTSECRETEXPIRES,
    });
    res.cookie("jwt", jwt_, {
        expires: new Date(
            Date.now() + process.env.COOKIESEXPIRES * 24 * 60 * 60000
        ),
        httpOnly: false,
        secure: false,
    });
    res.status(statusCode).json({
        status: "success",
        user,
        jwt: jwt_,
    });
}
const login = catchAsync(async (req, res, next) => {
    const { email, password } = req.body;
    if (!email || !password)
        return next(
            new AppError(400, "you should provide your email and password")
        );
    const user = await User.findOne({ email }).select("+password");
    if (!user || !(await user.isCorrectPassword(password)))
        return next(new AppError(400, "incorrect email or password "));
    passport(res, user, 200);
});

in my next.js app i try to send a login request

const Login = () => {
    const email = useRef(null);
    const password = useRef(null);
    return (
        <form
            onSubmit={async (e) => {
                e.preventDefault();
                const res = await axios.post(
                    "http://127.0.0.1:3000/api/v1/users/login",
                    {
                        email: email.current.value,
                        password: password.current.value,
                    },
                    { withCredentials: true }
                );
            }}
        >
            <input ref={email} />
            <input ref={password} />
            <button>login</button>
        </form>
    );
};
export default Login;

the problem is the Cookie found in the res headers but it's not loaded by the browser !!

this is my the cors config in my app.js:

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

app.use(
    cors({
        withCredentials: true,
        credentials: true,
        origin: "http://localhost:3001",
    })
);

it would be helpful to know where is exactly the problem

zaouich
  • 3
  • 2

1 Answers1

0

I think you should use port 3000 in the cors config. Even if you face any issue do refer this