Home > Enterprise >  Cannot set headers after they are sent to the client - error in my console
Cannot set headers after they are sent to the client - error in my console

Time:07-27

I`m getting the "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" error in my code. Please, help me to understand what I'm doing wrong.

I try to use Passport middleware in my app

passport.strategy

passport.use(
  new LocalStrategy(
    {
      usernameField: "signinEmail",
      passwordField: "signinPassword",
    },
    //  Passport verify callback
    async (email, password, done) => {
      const user = await userService.getByEmailOrPhone(email);
      if (user) {
        if (user.password) {
          bcrypt.compare(password, user.password, (err, res) => {
            if (!err) {
              if (res) {
                return done(null, user);
              }
              return done(null, false, { message: "Incorrect password" });
            }
            console.log(err);
          });
        }
        return done(null, false, {
          message: "Please login with Google or Facebook",
        });
      }
      return done(null, false, { message: "Incorrect login" });
    }
  )
);

Route with middleware

router.post(
  "/login",
  passport.authenticate("local"),
  validationMiddleware({
    signinEmail: ["required", "email"],
    signinPassword: ["required", "min:6"],
  }),
  asyncHandler(async (err, req, res) => {
    // if (err) {
    //   console.log(res);
    // }

    const { accessToken, refreshToken } = await authService.authorizeById(
      req.req.user.user_id
    );
    console.log("user", accessToken);
    if (accessToken) {
      return res.send({
        accessToken,
        refreshToken,
        success: true,
      });
    }
    throw new UnauthorizedException("");
  })
);

I will be glad if someone helps.

CodePudding user response:

You should add corresponding else branch of if in your strategy, You should write it as,

passport.use(
  new LocalStrategy(
    {
      usernameField: 'signinEmail',
      passwordField: 'signinPassword',
    },
    //  Passport verify callback
    async (email, password, done) => {
      const user = await userService.getByEmailOrPhone(email);
      if (user) {
        if (user.password) {
          bcrypt.compare(password, user.password, (err, res) => {
            if (!err) {
              if (res) {
                return done(null, user);
              }
              return done(null, false, { message: 'Incorrect password' });
            }
            console.log(err);
          });
        } else {
          return done(null, false, {
            message: 'Please login with Google or Facebook',
          });
        }
      } else {
        return done(null, false, { message: 'Incorrect login' });
      }
    }
  )
);
  • Related