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

175
Visualizações
How to make it more cleaner and efficient and what are the practices to follow?

I'm building a user auth in the backend. I created a post method for registering a new user

userRouter.post("/", expressAsyncHandler(async (req, res) =>
{
  try {
        const { name, email, password } = req.body;
        const userExists = await User.findOne({ email });
        if (userExists) {
          res.status(400).json({ message: "User already exists" });
        }
        const user = await User.create({
          name,
          email,
          password,
        });

        if (user) {
          res.status(201).json({
            data: {
              _id: user._id,
              name: user.name,
              email: user.email,
              token: generateToken(user._id),
            },
          });
        } else {
          res.status(400).json({ message: "Registration failed" });
        }
  } catch (error) {
      res.status(500).json({message:error.message})
  }
}))

It is working but shows

Cannot set headers after they send it to the client

I'm feeling a little uncomfortable with this code. so how can I make the code cleaner and more efficient? what are the best practices to follow?

Thanks in advance :)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

two possible error.

  1. if you use middleware that add status header.
  2. "if (user) { res.status(201).json({....blabla" after status 201, if json fails then catch also add status(500)
about 4 years ago · Juan Pablo Isaza Relatório

0

Cannot set headers after they send it to the client

It happens when you are trying to set headers again. And in your case, it might be happening when you send the response and it breaks you again send or reset headers i.e status code in the catch block.

You can do one thing by adding console.log before the responses you are sending to debug it and you will be able to see what is causing it.

Also, you can check this link for more details before directly jumping into debugging.

about 4 years ago · Juan Pablo Isaza Relatório

0

Because if your API run successfully then you have to put (200) instead of (201) because if your API sends a request then the API response code is 200.

enter image description here

see in the image if you send a request in postman they also give status 200

I hope it's working for you.

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