-1

I am using the middleware function to get the user id from the jwt token and it is working completely fine but I want it to send a response when there is no jwt header in the request which it's doing. Here is the code:

const jwt = require("jsonwebtoken");

const fetchuser = (req, res, next) => {
  const jwtToken = req.header("jwt-token");
  if (!jwtToken) {
    console.log(2);
    return res
      .status(401)
      .status({ error: "This action requires the user to login" });
  }
  try {
    const data = jwt.verify(jwtToken, process.env.JWT_SECRET);
    if (data.user) {
      if (data.user.status === 1) {
        req.user = data.user;
      } else {
        return res.status(500).status({ error: "User account is disabled" });
      }
    } else {
      return res
        .status(401)
        .status({ error: "This action requires the user to login" });
    }

    next();
  } catch (error) {
    return res
      .status(401)
      .status({ error: "This action requires the user to login" });
  }
};

module.exports = fetchuser;

It's definitely going in the first if block as required when the header is absent but it's not sending the response back, the request keeps buffering

robertklep
  • 198,204
  • 35
  • 394
  • 381
yagyesh
  • 94
  • 7
  • Might you please [edit] your question to include your code as **text** rather than as a screenshot? On stack overflow images should not be used for textual content, see [*Discourage screenshots of code and/or errors*](https://meta.stackoverflow.com/a/307500) and [*Why not upload images of code on SO when asking a question*](https://meta.stackoverflow.com/a/285557) for why. For instructions on formatting see *[How do I format my code blocks?](https://meta.stackexchange.com/q/22186)*. A [mcve] showing what you have tried that did not work would maximize your chances of getting help. See [ask]. – dbc Sep 02 '22 at 15:25
  • Sorry about that, I changed it to text format – yagyesh Sep 02 '22 at 15:28
  • 1
    ```return res.status(401).status({ error: "This action requires the user to login" });``` Maybe a typo here. the second `status` should be `json` ? – Đăng Khoa Đinh Sep 02 '22 at 15:57
  • 1
    @ĐăngKhoaĐinh that's indeed the issue, feel free to make it an answer :D – robertklep Sep 02 '22 at 15:58

1 Answers1

2

This block is where the problem occurs:

return res
      .status(401)
      .status({ error: "This action requires the user to login" });

status is used to set the http status code for the response. To send the response to the client, you can use json.

It should be:

return res
      .status(401)
      .json({ error: "This action requires the user to login" });

You need to do the same thing for other blocks.

Đăng Khoa Đinh
  • 5,038
  • 3
  • 15
  • 33