我正在尝试在 React-Express Web App 上创建注销功能。但它并没有清除我的cookie。
设置cookie时的代码
res.cookie('!', t, {
maxAge: 1000 * 60 * 60 * 24 * 30,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: "strict",
priority: "high"
})
res.status(200).json()
删除 cookie 的代码
const SignOut = (_: Request, res: Response) => {
res.clearCookie('!')
res.status(200).json()
}
export default SignOut
路线
import RegCon from '../controllers/Register'
import LogCon from '../controllers/Login'
import OutCon from '../controllers/SignOut'
const router = express.Router({
caseSensitive: true,
strict: true
})
router.post('/API/register', RegCon)
router.post('/API/login', LogCon)
router.delete('/API/signout', OutCon)
反应注销处理程序
const handleSignOut = async () => {
try {
await axios.delete('http://localhost:3001/API/signout')
// location.href = '/'
} catch (err) {
const XR = err as AxiosError
alert(XR.response!.statusText)
}
}
让我更困惑的是它没有落入陷阱,它实际上成功了,但它没有清除我的 cookie here
谁能解释一下为什么?
根据 Express documentumnetation here,您需要传递选项参数,该参数应与您在设置 cookie 时定义的参数相同,但
expires
和 maxAge
除外。
因此,您的注销功能应如下所示:
const SignOut = (_: Request, res: Response) => {
res.clearCookie('!', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: "strict",
priority: "high",
path: '/' // add this path when setting the cookie as well
});
res.status(200).json()
}