Postgres field not updating in node.js

Viewed 12

I am trying to make a profile update page with PERN and it is not working. For some reason, when I update it once on the frontend, it works, but when I do it again, it does not update. (By the way, I am using jwt)

Here is my express server code for the token checking:

const checkToken = (req, res, next) => {
    const tokenHeader = req.headers['authorization']

    if (!tokenHeader) return res.status(200).send({
        'error': 'Token not found'
    })

    const token = tokenHeader.split(' ')[1]

    jwt.verify(token, process.env.JWT_ACCESS_TOKEN_SECRET, (err, user) => {
        if (err) {
            console.log('jwt err: ', err)
            return res.status(200).send({
                'error': 'Unauthorized'
            })
        }

        req.user = user

        return next()
    })
}

For getting profile info:

app.get('/api/auth/user/profile', checkToken, (req, res) => {
    pool.query('SELECT * FROM "user" WHERE username = $1', [req.user.username], (err, results) => {
        if (err) throw err
        res.json(results.rows[0] ?? {
            'error': "Something went wrong"
        })
    })
})

And for updating the profile info:

app.patch('/api/auth/update/', checkToken, (req, res) => {
    if (!req.body.username) {
        return res.status(200).send({
            'error': 'Username is required'
        })
    }

    if (!req.body.name) {
        return res.status(200).send({
            'error': 'Name is required'
        })
    }

    if (!req.body.age) {
        return res.status(200).send({
            'error': 'Age is required'
        })
    }

    if (req.body.password) {
        return res.status(200).send({
            'error': 'Change password is not here'
        })
    }

    if (!req.body.email) {
        return res.status(200).send({
            'error': 'Email is required'
        })
    }

    const { email, name, username, age } = req.body

    pool.query('UPDATE "user" SET name = $1, email = $2, age = $3, username = $4 WHERE username = $5', [name, email, age, username, req.user.username], (err, results) => {
        if (err) throw err

        const accessToken = generateToken({ username: username }, tokenTypes.access)

        console.log('update results', results.rowCount)
        console.log('username', username)

        return res.status(200).send({
            'message': "User updated successfully!",
            'accessToken': accessToken
        })
    })
})

I know that when I console.log results.rowCount when I update, it will show me how many rows I updated. Well, the first time I update, it says 1. But for the second time, it says 0. So, when I try to update the info for the 3rd time, it doesn't work. Because the token's info changes, but not the info in the database. So it doesn't find the profile info and eventually just keeps on loading. Can anyone tell me how to fix this?

0 Answers
Related