【发布时间】:2021-07-28 18:08:39
【问题描述】:
我现在有点迷失在自己的代码中,我需要亮度。
我在登录时尝试使用 JWT 设置 cookie。这是我的代码:
我的路线:
router.post('/signin', user.signIn);
我的控制器:
const jwtExpire = 3 * 23 * 60 * 60 * 1000
const createToken = (id) => {
return jwt.sign({ id }, process.env.TOKEN_SECRET, {
expiresIn: jwtExpire
})
}
module.exports.signIn = async (req, res) => {
const { email, password } = req.body
try {
const user = await UserModel.login(email, password)
const token = createToken(user._id)
res.cookie('jwt', token, { httpOnly: true, jwtExpire })
res.status(200).json({ user: user._id })
} catch (err) {
const errors = signInErrors(err)
res.status(200).json({ errors })
}
}
我的表格:
<form id="signin-block" style="display: block;" class="p-4 mx-auto">
<h2 class="text-center my-4 underline">Se connecter</h2>
<div class="input-group">
<input id="email" type="text" class="form-control" name="email" placeholder="E-mail">
</div>
<div class="input-group">
<input id="password" type="password" class="form-control" name="password"
placeholder="Mot de passe">
</div>
<button type="submit" class="btn btn-primary mt-4" id="submit">Me connecter</button>
</form>
我的登录功能:
logInBlock.addEventListener('submit', function (e) {
e.preventDefault()
const email = e.target[0].value
const password = e.target[1].value
axios({
method: 'post',
url: 'http://localhost:5000/api/signin',
data: {
email: email,
password: password
}
}).then((res) => console.log(res))
})
使用 POSTMAN,cookie 被设置。所以缺少的是我自己的要求,但我不明白是什么。有什么想法吗?
【问题讨论】:
-
使用 POSTMAN ...换句话说,这可能是一个 CORS 错误 - 检查浏览器开发者控制台是否有错误,特别是那些提到 CORS 的错误
-
@Bravo CORS 没问题,我的状态为 200。我认为我的日志工作正常,只是没有设置 cookie
-
{ httpOnly: true, jwtExpire }应该是{ httpOnly: true, maxAge: jwtExpire }。让我们知道这是否有帮助。 -
好的,所以您在登录响应中根本看不到 cookie?
-
@WiktorZychla 不是,不是。问题出在我的 axios 请求中,我想我必须设置 cookie 但我看不到如何
标签: javascript authentication jwt