无法删除express中的cookie

问题描述 投票:0回答:9

非常简单。我在我的

/user/login
路线中设置了这样的cookie:

if (rememberMe) {
    console.log('Login will remembered.');
    res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' });
}
else {
    console.log('Login will NOT be remembered.');
}

我已经为 cookie 解析器设置了秘密:

app.use(cookieParser('shhh!'));

非常基本的东西。一切都很顺利,因为我能够检索我存储在 cookie 中的任何内容:

app.use(function (req, res, next) {
    if (req.signedCookies.user) {
        console.log('Cookie exists!');
        req.session.user = req.signedCookies.user;
    }
    else {
        console.log('No cookie found.');
    }

    next();
});

这个中间件在其他任何事情之前被调用,因此为了论证“Cookie 存在!”如果 cookie 有效,则始终记录在我的控制台中。

问题是当我尝试删除 cookie 时。我尝试过

res.clearCookie('user')
res.cookie('user', '', { expires: new Date() })
,并且尝试传递相同的标志(我在
res.cookie()
中传递给
/user/login
)。我尝试过使用这些方法的组合,但没有任何效果。

目前,我能够清除 cookie(并且不会收到“Cookie 存在!”日志消息)的唯一方法是清除浏览器历史记录。这是我的注销路线:

route.get('/user/logout', function (req, res, next) {
    res.clearCookie('user');
    req.session.destroy();
    util.response.ok(res, 'Successfully logged out.');
});

好像我连cookie值都修改不了;我放了

res.cookie('user', {}, { signed: true, httpOnly: true, path: '/' })

在我的注销路线中,但 cookie 值保持不变。

javascript node.js express cookies
9个回答
21
投票

经过漫长而烦人的时间后,我意识到我的前端没有将 cookie 发送到终点,因为我正在尝试清除 cookie...

在服务器上:

function logout(req, res) {
  res.clearCookie('mlcl');
  return res.sendStatus(200);
}

在前端,

fetch('/logout', { method: 'POST', credentials: 'same-origin' })

添加“凭据:'同源'”使clearCookie对我有用。如果未发送 cookie,则无需清除任何内容。

我希望这有帮助。我希望我早点发现这个......


18
投票

尽管这不会帮助这个问题的作者,但我希望这可以帮助别人。 我遇到了同样的问题,无法删除使用 Express api 的 React 应用程序中的 cookie。我使用了 axios,几个小时后我终于能够修复它。

await axios.post('http://localhost:4000/api/logout', { } , { withCredentials: true })

{ withCredentials: true }
使它对我有用。

这是我的快递代码:

 const logOutUser = (req, res) => {
  res.clearCookie('username')
  res.clearCookie('logedIn')
  res.status(200).json('User Logged out')
}

6
投票

根据(广泛的)搜索和我脑海中突然出现的一个随机想法,答案是使用

res.clearCookie('<token_name>',{path:'/',domain:'<your domain name which is set in the cookie>'});

    res.clearCookie('_random_cookie_name',{path:'/',domain:'.awesomedomain.co'}); 

请注意 cookie 中指定的 .,因为我们将其用于子域(您也可以将其用于不带点的子域,但使用它更安全)。

TLDR;您必须在后端提供路由和域:,以便向前端中的同一端点发出请求。


4
投票

确保您发送的凭据需要清除

即使它只是一个

/logout
端点,您仍然需要发送凭据。

// FRONT END
let logOut = () => {

  fetch('logout', {
    method: 'get',
    credentials: 'include', // <--- YOU NEED THIS LINE
    redirect: "follow"
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  });

}


// BACK END
app.get('/logout', (req, res) => {
  res.clearCookie('token');
  return res.status(200).redirect('/login');
});

2
投票

做了一场噩梦,让这个也能正常工作,这对我有用,希望对某人有帮助。

快速路由器

router.post('/logout', (req, res) => {
    res.clearCookie('github-token', {
        domain: 'www.example.com',
        path: '/'
    });
    return res.status(200).json({
        status: 'success',
        message: 'Logged out...'
    });
});

React 前端处理注销。

const handleLogout = async () => {
    const logout = await fetch('/logout', {
        method: 'POST',
        credentials: 'include',
    });
    if (logout.status === 200) {
        localStorage.clear();
        alert('Logged out');
    } else {
        alert('Error logging out');
    }
};

我正在像这样在我的身份验证调用中设置 cookie。

res.cookie('github-token', token, {
    httpOnly: true,
    domain: 'www.example.com',
    secure: true
});

重要的是您需要在clearCookie方法中添加路径和域。


1
投票

2022 年 11 月(Chrome)——什么对我有用

前端:

const logOut = async () =>{
  await axios.post(LOGOUT_URL, {}, {withCredentials: true}) // <-- POST METHOD, WITH CREDENTIALS IN BODY
}

后端:

res.clearCookie('jwt') // <- NO EXTRA OPTIONS NEEDED, EVEN THOUGH HTTPONLY WAS SET
return res.sendStatus(204)

0
投票

路径需要正确。就我而言,这是路径中的拼写错误


0
投票

我对此很陌生,但添加返回(

return res.sendStatus(204);
)到后端函数是为我删除cookie的原因,希望它有帮助。 如果不返回,它不会删除 cookie,而只会记录“会话结束”

 app.post("/logout", (req, res) => {
  if (req.session.user && req.cookies.user_sid) {
    res.clearCookie("user_sid");
    console.log("session over");
    return res.sendStatus(204);
  } else {
    console.log("error");
  }
});

0
投票

在我的例子中,我使用一个变量作为可重用变量,如下所示

const refreshTokenOptions = {
  httpOnly: true,
  secure: true,
  maxAge: 604800000, // (1 week)
};

// in api endpoint
res.cookie('refreshToken', refreshToken, refreshTokenOptions);

在注销端点中。我像这样传递相同的变量。这不起作用

  res.clearCookie('refreshToken', refreshTokenOptions);

这样设置后,就成功了

  res.clearCookie('refreshToken', { httpOnly: true, secure: true });

我认为这与maxAge有关。在清除 cookie 时,我们必须删除 maxAge

© www.soinside.com 2019 - 2024. All rights reserved.