Home > Enterprise >  Express middleware not sending back body data
Express middleware not sending back body data

Time:01-22

I created an express middleware that checks the user token as authorization before proceeding:

import jwt from 'jsonwebtoken';

export const verifyAuthorization = async (req, res, next) => {
    try {
        const token = req.headers.authorization.split(' ')[1];
        if (!token) return res.status(403).send({ error: 'Not authorized' });
        const tokenData = jwt.verify(token, 'secret_code');
        req.userData = {
            userId: tokenData.userId,
            fullName: tokenData.fullName,
            section: tokenData.section,
            groupId: tokenData.groupId,
            level: tokenData.level,
        };
        next();
    } catch (error) {
        console.log(error);
        res.status(403).send({ error: 'Not authorized' });
    }
};

I applied this middleware for all endpoints of a route like this:

import { Router } from 'express';
const router = Router();
import item from '../controllers/item_controllers.js';
import { verifyAuthorization } from '../middleware/verifyAuthorization.js';

router.use(verifyAuthorization);

router.post('/all', item.all);
router.post('/new', item.newOne);
router.post('/edit', item.edit);

export default router;

The problem is that if there's a problem with the authorization, it sends back the status code but not the body. In my React app I see the 403 error on console but it logs the response as "undefined". The controller functions send back the json body perfectly fine. I don't understand what's wrong with the middleware here.

Any ideas??

Thank you

CodePudding user response:

I fixed it. There was a problem with the custom hook I created for http requests. It was finishing the requests on error without sending back any data. That's why I saw the status code error but not the body. I logged the response on the hook and it gets there. I just deleted the "return" keyword on the error block in the hook and I got the response's body perfectly. Thank you everybody for your time.

CodePudding user response:

It looks like the issue is that the middleware is sending a response with a status code of 403, but no JSON body. This is causing the response to be "undefined" in your React app.

One possible solution would be to make sure that the middleware sends a JSON body along with the status code. You can do this by modifying the following line:

return res.status(403).send({ error: 'Not authorized' });

to:

return res.status(403).json({ error: 'Not authorized' });

This way, the middleware will send a JSON response with a status code of 403 and a body containing the error message.

Additionally, you can also add a check for the 'req.headers.authorization' exist or not before splitting it.

 if (!req.headers.authorization) return res.status(403).json({ error: 'Not authorized' });
 const token = req.headers.authorization.split(' ')[1];

This should make sure that the middleware sends the proper JSON response with the correct status code and error message, and the React app should be able to properly handle the response.

  • Related