Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
Cannot set headers after they are sent to the client - google sign in error

I am working through an authentication application from devchallenges.io. So far, I've been able to set up the basic login with email and password. I'm now trying to set up google login auth. When testing the server with Postman I get the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. The app seems to stills work as a json web token is returned so not too sure why I'm getting this error.

enter image description here

server.js

// @route    POST auth/google
// @desc     auth user with google
// @access   Public
app.post('/auth/google', (req, res) => {
  const { token } = req.body;
  const CLIENT_ID =
    '1068367393637-jtuoidgq5mi5krd5q31u9ncjovt3fvgh.apps.googleusercontent.com';
  const client = new OAuth2Client(CLIENT_ID);

  let { email, name, picture, password } = '';

  async function verify() {
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID,
    });
    const payload = ticket.getPayload();
    const userid = payload['sub'];

    email = payload.email;
    name = payload.name;
    picture = payload.picture;
    password = generator.generateMultiple({
      length: 6,
    });

    try {
      // See if user exists
      let user = await AuthUser.findOne({ email });
      if (user) {
        // Return jsonwebtoken
        const payload = {
          user: {
            id: user.id,
          },
        };

        jwt.sign(
          payload,
          config.get('jwtSecret'),
          { expiresIn: '5 days' },
          (err, token) => {
            if (err) throw err;
            res.json({ token });
          }
        );
      }

      user = new AuthUser({
        name,
        email,
        picture,
        password,
      });
      // Encrypt password
      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);
      await user.save();
      // Return jsonwebtoken
      const payload = {
        user: {
          id: user.id,
        },
      };
      jwt.sign(
        payload,
        config.get('jwtSecret'),
        { expiresIn: '5 days' },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
    } catch (error) {
      console.error(error.message);
      res.status(500).send('Server error');
    }
  }
  verify().catch(console.error);
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

All I had to do was add an else conditional statement.

if (user) {
        // Return jsonwebtoken
        const payload = {
          user: {
            id: user.id,
          },
        };

        jwt.sign(
          payload,
          config.get('jwtSecret'),
          { expiresIn: '5 days' },
          (err, token) => {
            if (err) throw err;
            res.json({ token });
          }
        );
      } else {
        user = new AuthUser({
          name,
          email,
          picture,
          password,
        });
        // Encrypt password
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(password, salt);
        await user.save();
        // Return jsonwebtoken
        const payload = {
          user: {
            id: user.id,
          },
        };
        jwt.sign(
          payload,
          config.get('jwtSecret'),
          { expiresIn: '5 days' },
          (err, token) => {
            if (err) throw err;
            res.json({ token });
          }
        );
      }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda