【问题标题】:Why my API is not working anymor after using JWT?为什么我的 API 在使用 JWT 后不再工作?
【发布时间】: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


【解决方案1】:

您正在定义一个函数 authJwt 但从未调用它。

改变

app.use(authJwt);

app.use(authJwt());

在您只是传递它之前,现在您正在调用它,返回 expressJWT 中间人。

【讨论】:

  • 是的!很好,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
相关资源
最近更新 更多