【发布时间】:2021-10-23 09:32:55
【问题描述】:
我正在为我的前端应用程序创建一个 API 后端。在 Postman 中测试 GET 和 POST 请求时一切正常。但是在我尝试使其安全之后,它不再起作用,请求正在运行,正在运行......并且什么都不返回,甚至没有返回错误消息。 我创建了一个 jwt.js:
const expressJwt = require('express-jwt');
// creating the function
const authJwt = () => {
// use the secret
const secret = process.env.secret_key;
// returning expressJwt to use the secret and the algorithms
return expressJwt({
secret,
algorithms: ['HS256']
})
}
module.exports = authJwt;
我用以下内容更新了我的 index.js:
const authJwt = require('./helpers/jwt');
app.use(authJwt);
我创建如下获取请求:
// getting the list of users
router.get(`/`, async (req, res) =>{
const userList = await User.find().select('-passwordHash');
if(!userList) {
res.status(500).json({success: false})
}
return res.status(200).send(userList)
})
最后,我为登录创建了 post 请求:
// login the user api
router.post(`/login`, async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user)
return res.status(404).send({ message: 'User was not found' })
if (user && bcrypt.compareSync(password, user.passwordHash)) {
const secret = process.env.secret_key
const token = jwt.sign(
{
userId: user.id,
},
secret,
{ expiresIn: '1d' }
)
return res.status(200).send({ user: user.email, token: token })
} else {
return res.status(404).send({ message: 'Wrong email or password' })
}
})
【问题讨论】:
-
试试
const authJwt = () => { .... your code .... }();- 如果可行,我会解释原因
标签: javascript node.js jwt express-jwt