Home > OS >  Trying To Incorporate Tokens Into Sign Up
Trying To Incorporate Tokens Into Sign Up

Time:05-20

I am trying to create a token from JWT when a user signs up for my application but I get the error, Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I think there is an issue with the structure of my code. How can I fix this issue?

//sign up request
exports.signup = async (req, res, next)=> {
    
    const {email} = req.body;
    const userExist = await User.findOne({email});

    if (userExist) {
        return next(new ErrorResponse(`Email already exists`, 404))
    }

    
    try {
        const user = await User.create(req.body);
        res.status(201).json({
            success: true,
            user
        })

        generateToken(user, 201, res);


    } catch (error) {
       console.log(error);
       next(error);
    }
}

//generate token method
const generateToken = async (user, statusCode, res) => {
    const token = await user.jwtGenerateToken();
    var hour = 3600000;
    const options = {
        httpOnly: true,
        expires: new Date(Date.now()   hour)
    };
    res.status(statusCode)
    .cookie('token', token, options)
    .json({success: true, token})
}

CodePudding user response:

you are trying to send the response twice. and then in generateToken method. Keep it at one place, the error will go away.

CodePudding user response:

First generate the token and next send the response

 generateToken(user, 201, res);

 res.status(201).json({
            success: true,
            user
        })

You can return value from the token and then send it using response or you can just send it from the generateToken function. Here you are trying to use the response again though you have sent it once hence resulting in error.

  • Related