res.clearCookie function doesn't delete cookies

三世轮回 提交于 2021-01-27 05:52:53

问题


I am creating an authorization system for my express (with typescript) application and I use JWT and save them into cookies to keep the user logged in. I have a problem with the logout part and res.clearCookie() doesn't delete cookies.

I have used cookie-parser in the index file and I have tried resetting the cookie with an empty value or expiration date of now but it doesn't work for me. As I stated above res.clearCookie("jwt") doesnt work either. All dependencies are up-to-date.

Login and Login Verification works fine and I can set and read [and decode] the JWT properly.

Main Part of Login Code

res.cookie("jwt", token, {
   httpOnly: true,
   expires: new Date(
       Date.now() + 1000 * 86400 * stayLoggedInDays
   )
}).send("Message: Login successful");

Logout Code

router.post(
  "/logout",
  (req, res, next) => {
    res.clearCookie("jwt");
    next();
  },
  (req, res) => {
    console.log(req.cookies);
    res.end("finish");  
  }
);

After Logout I still can see the user profile but if I delete the cookie manually from postman the profile page won't show any information so my conclusion is that express cannot clear cookies.


回答1:


I believe your issue is that you are not passing the options parameter into clearCookie() and the client is not clearing the cookie as it is not identical. Per the Express documentation:

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

Also found a GitHub issue on the express repo which states the same and shows an example of passing the domain and path:

res.clearCookie('my_cookie', {domain: COOKIE_DOMAIN, path: COOKIE_PATH});


来源:https://stackoverflow.com/questions/57791209/res-clearcookie-function-doesnt-delete-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!