推荐答案
在 Express 中,可以通过 res.clearCookie() 方法来删除客户端的 Cookie。具体用法如下:
res.clearCookie('cookieName');如果需要删除带有特定选项(如 path 或 domain)的 Cookie,可以在 clearCookie 方法中传递相同的选项:
res.clearCookie('cookieName', { path: '/admin', domain: 'example.com' });本题详细解读
1. res.clearCookie() 方法的作用
res.clearCookie() 方法用于删除客户端浏览器中的指定 Cookie。它通过设置 Cookie 的过期时间为过去的时间来实现删除操作。
2. 参数说明
- cookieName: 要删除的 Cookie 的名称。
- options: 可选参数,用于指定与 Cookie 相关的选项,如
path、domain等。这些选项必须与设置 Cookie 时使用的选项一致,否则可能无法正确删除 Cookie。
3. 示例代码
假设我们之前在客户端设置了一个名为 userToken 的 Cookie,现在需要删除它:
app.get('/logout', (req, res) => {
res.clearCookie('userToken');
res.send('Logged out successfully');
});如果 userToken Cookie 设置了特定的路径或域,删除时需要传递相同的选项:
app.get('/logout', (req, res) => {
res.clearCookie('userToken', { path: '/admin', domain: 'example.com' });
res.send('Logged out successfully');
});4. 注意事项
- 删除 Cookie 时,
path和domain选项必须与设置 Cookie 时使用的选项一致,否则删除操作可能无效。 res.clearCookie()方法只是告诉客户端浏览器删除指定的 Cookie,实际的删除操作由浏览器完成。