Home > Software design >  How to Fix Headers Already Sent to Client in NodeAPI with Angular
How to Fix Headers Already Sent to Client in NodeAPI with Angular

Time:12-31

I am getting the following error on my node api, which is really just console logging the request at this point.

    router.get('/booksByISBN', checkRole, async (req, res) => {
        console.log(req.params)
        return res.sendStatus(200);
    });
node:internal/errors:484
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I believe the issue is because of pre-flight CORS data, but no clue how to fix it.

There is one API call in my Angular 15 application, but upon inspection of the Network tab, I see two api calls are actually being made to my endpoint.

enter image description here

I understand this is because of the CORS options request, but I don't know how to fix it to let the API go through.

CheckRole function

    var checkRole = async function CheckRoleAuth (req, res, next) {
        try {
            const token = req.headers.authorization.split(' ')[1];
            const decodedToken = jwt.verify(token, envs.jwtSecret);
    
            await User.findById(decodedToken.userId)
                .then(foundUser => {
                    if (foundUser) {
                        if (foundUser.role != null || foundUser.role != '') {
                            if (foundUser.role.includes('Admin'))
                            {
                                req.userData = {
                                    email: decodedToken.email,
                                    id: decodedToken.id
                                };
                                next();
                            } else {
                                return res.sendStatus(401);
                            }
                        } else {
                            return res.sendStatus(401);
                        }
                    }
                })
                .catch(err => {
                    return res.sendStatus(401);
                });
    
        } catch (error) {
            return res.sendStatus(401);
        }
    }

CodePudding user response:

You are combining async/await with then/catch in your checkRole middlware, so probably both your checkRole middleware and your endpoint handler try to send back the response.

Refactor your checkRole middleware like this:

const checkRole = async function CheckRoleAuth(req, res, next) {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decodedToken = jwt.verify(token, envs.jwtSecret);

    const user = await User.findById(decodedToken.userId).lean();

    if (!user) return res.sendStatus(401);

    if (!user?.role?.includes('Admin')) return res.sendStatus(403);

    req.userData = { email: decodedToken.email, id: decodedToken.id };
    next();
  } catch (error) {
    return res.sendStatus(401);
  }
};
  • Related