Home > Software engineering >  App crashes, after the verification of jwt token
App crashes, after the verification of jwt token

Time:10-23

Firstly, I added the token in post request, then it successfully gives the response message "Email verified".

Click here: to see response message

But after, the user's jwt token is verified, then suddenly app crashes and throws the error:

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:363:5)
    at ServerResponse.setHeader (node:_http_outgoing:574:11)
    at ServerResponse.header (E:\WEB_DEV\frontend2\backend\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (E:\WEB_DEV\frontend2\backend\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (E:\WEB_DEV\frontend2\backend\node_modules\express\lib\response.js:267:15)
    at E:\WEB_DEV\frontend2\backend\middleware\authMiddleware.js:28:37
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

Here is the token verification code:

const jwt = require('jsonwebtoken');
const client = require('../configs/database');

exports.verifyToken = (req, res) => {
    const token = req.headers.authorization;
    jwt.verify(token, process.env.SECRET_KEY, (err, decoded) => {
        if (err) {
            res.status(500).json({
                error: "Server error found"
            })
        }
        console.log(decoded.email);
        const userEmail = decoded.email;
        client.query(`SELECT * FROM login WHERE email = '${userEmail}'`)
            .then((data) => {
                // console.log(data);
                if (data.rows.length == 0) {
                    res.status(404).send("Token not verified");
                }
                else {
                    req.email = userEmail;
                    res.status(200).send("Email verified");
                    next();   //problem occurs here**
                }
            })
            .catch((err) => {
                if (err) {
                    res.status(500).json({
                        message: "Database error occurred",
                        error: err,
                    })
                }

            })
    })
}

Cause of crash of app, "Middleware working" isn't displayed.

const express = require('express')
const router = express.Router();
const { verifyToken } = require('../middleware/authMiddleware');
// const { addProducts } = require('../controllers/products');


router.post("/add", verifyToken, (req, res) => {
    res.send("Middleware working");
})

CodePudding user response:

You should not use next() after sending a response.

So the solution here would be to use next() when the token is verified. So your req, res goes on to the /add route.

If the token is not valid you send a response like you do now.

So just remove res.status(200).send("Email verified");

  • Related