skip to Main Content

I am having an error when people register or try to login, it throws me the following error, but it happens sometimes,
enter image description here

my code is the following
enter image description here

enter image description here

2

Answers


  1. res.send can only be called once. In the bcrypt.compare callback, res.send is called twice (for both statuses 201 and 200). Also, you must use a return statement after res.send or return res.send. This is because the code continues after executing the function.

    You can also:

    • Change the status code for a false result to 400 – best practice
    • Remove the 500 as it is never reached.

    I have applied these changes to my code below.

    Fixed code:

    ...
    if (!result) {
        return res.status(400).json({
                error: "User or password invalid",
            })
        }
    
        const userForToken = {
            id: users._id,
            name: users.name,
        }
    
        const token = jwt.sign(userForToken, process.env.SECRET)
    
        res.status(200).send({
            name: users.name,
            email: users.email,
            token,
            result: true,
            id: users._id,
        })
    }
    ...
    
    Login or Signup to reply.
  2. res.status().send() doesn’t exit the function like return, so you cannot use it like return. You are getting this error because you are sending a response more than once.

    I would suggest structuring your logic to build a Response object, then send the response once it is built.

    Example Response Object:

    class Response{
        constructor(status, body){
            this.status = status;
            this.body = body;
        }
    }
    

    Example Usage:

    ...
    
    var response;
    
    if(!result){
        response = new Response(201, {error: "User or password invalid"});
    }
    
    if(!response){
        const userForToken = {
            id: users._id,
            name: users.name,
        }
    
        const token = jwt.sign(userForToken, process.env.SECRET)
    
        response = new Response(200, {name: users.name, email: users.email, token: token, result: true, id: users._id})
    }
    
    res.status(response.status).send(response.body);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search