0

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 :)

aravind ks
  • 612
  • 7
  • 18

3 Answers3

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)
grijjLY
  • 87
  • 4
  • can give a context please. I can't figure it out :( – aravind ks Jan 25 '22 at 06:04
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '22 at 12:22
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.

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • okay, it means that if an user exists, it will set the status code into 400 and also in the catch section it try to update the status code to 500 even after it sends to the client. so should I remove the try-catch block? – aravind ks Jan 25 '22 at 06:07
  • Another option i think that using a custom error handler in between the req-res cycle and let that error handler to handle the error instead of try catch . is it a good method ? – aravind ks Jan 25 '22 at 06:09
  • Yes, handle error at once place. First try to find out what is breaking and fix it. Removing try/catch is not a good option. Keep it and try to see what is breaking when you send the response at first place. – Apoorva Chikara Jan 25 '22 at 06:57
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.

divyraj
  • 191
  • 2
  • 14
  • When you create a resource, you send 201 status code. Check [this](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201#:~:text=The%20HTTP%20201%20Created%20success,the%20creation%20of%20a%20resource.) – Apoorva Chikara Jan 25 '22 at 06:59