skip to Main Content

Sending a logout request to my server but I’m never getting a reply. The logout function is being called and the userID key is being deleted from my redis cache but I never get a response. Here’s my code.

export const logout = async (req, res) => {
  console.log("logout called");
  const { userID } = req.user;

  client.del(userID.toString, (err, reply) => {
    console.log("inside client.del");
    if (err) {
      return res.status(500);
    } else {
      return res.status(200);
    }
  });
};

2

Answers


  1. Because of callback, you should use promise

    export const logout = async (req, res) => {
        return new Promise((resolve,reject) => {
            console.log("logout called");
                const { userID } = req.user;
            
                client.del(userID.toString, (err, reply) => {
                console.log("inside client.del");
                if (err) {
                    reject(res.status(500));
                } else {
                    resolve(res.status(200));
                }
            });
        });
    }
    
    Login or Signup to reply.
  2. res.status() does not send a response from the server. All it does is set the status as a property on the response object that will go with some future call that actually sends the response.

    It is meant to be used in something like this:

    res.status(500).send("Database error");
    

    If you look at the Express doc for res.status(), you will see these examples:

    res.status(403).end()
    res.status(400).send('Bad Request')
    res.status(404).sendFile('/absolute/path/to/404.png')
    

    And, see that they all are followed by some other method that actually causes the response to be sent.


    And, if you still had any doubt, you can look in the Express code repository and see this:

    res.status = function status(code) {
      this.statusCode = code;
      return this;
    };
    

    Which shows that it’s just setting a property on the response object and not actually sending the response yet.


    You can use res.sendStatus() instead which will BOTH set the status and send the response:

    export const logout = (req, res) => {
      console.log("logout called");
      const { userID } = req.user;
    
      client.del(userID.toString, (err, reply) => {
        console.log("inside client.del");
        if (err) {
          res.sendStatus(500);
        } else {
          res.sendStatus(200);
        }
      });
    };
    

    Note, I removed the two return keywords since they don’t accomplish anything useful in this particular context.

    I also removed the async keyword from the function definition since it was not doing anything useful in this context.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search