下一个通过响应主体

I'm pretty new to JavaScript so I'm still trying to figure things out. In the app we use jwt to check if a token is valid. For this, the following function is created using a tutorial and some of my own experimentation:

function isAuthorized(req, res, next) {
    const bearerHeader = req.headers['authorization']

    if (typeof bearerHeader !== 'undefined') {
        let token = bearerHeader.split(' ')[1]
        let privateKey = 'secretkey'

        jwt.verify(token, privateKey, { algorithm: "HS256" }, (err) => {
            if (err) {
                res.sendStatus(403)
            }
            else {
                next()
            }
        })
    }
    else {
        res.sendStatus(403)
    }
}

When I then do a post call with some json payload in it, it will pass correctly in the following function:

app.post('/api/posts', isAuthorized, (req, res) => {
    res.json({
        message: 'Post created',
        request: req.body.username
    })
})

The only thing that doesn't seem to work is how to consult the json paybload in the body that was sent with the post call. It surely must be possible to have the middleware function isAuthorized have this data passed on.

评论