1

I am working on ReactJs and NodeJS and I am creating a signup page. I post data to server but it is always pending.

Which part did I do wrong? It would be nice if someone can help.

Front end:

const handleSubmit = (event) => {
    // prevent page refresh
    event.preventDefault();
    const newUserData = {
      name: name,
      email: email,
      password: password,
    };
    axios
      .post("/signup", newUserData)
      .then((res) => {
        console.log(res.data);
      })
      .catch((error) => {
        console.log(error);
      });
      setEmail("");
      setName("");
      setPassword("")
    console.log("form submitted ✅");
  };

Backend:

router.post("/signup", (req, res) => {
  const { name, email, password } = req.body;
  if (!email || !password || !name) {
    res.status(422).send({ error: "Please add all the fields" });
  }
  console.log(req.body);
  User.findOne({ email: email })
    .then((savedUser) => {
      if (savedUser) {
        res.status(422).send({ error: "Email already been used" });
      }
      bcrypt.hash(password, 12).then((hashedpassword) => {
        const user = new User({
          name,
          email,
          password: hashedpassword,
        });
        user
          .save()
          .then((user) => {
            res.json({ message: "Sign Up Successfully" });
          })
          .catch((err) => {
            console.log(err);
          });
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

in package.json i set proxy as

"proxy": "http://localhost:5000",
Arnab
  • 4,216
  • 2
  • 28
  • 50
Harris Ho
  • 11
  • 1
  • I tested the api through postman and I got the respond instantly. So I think maybe something I did wrong on the front-end part? – Harris Ho Dec 07 '22 at 01:41
  • Did you find out why? I'm having the same problem with calls to localhost. If I use any external address it works fine. – Tajs Feb 08 '23 at 18:26

3 Answers3

0

I guess you are using MongoDB as well, in that case keep in your mind that the findOne is async, so you need to use await before. And for to save data you need to use the .create() method from MongoDB, e.g.

router.post("/signup", async (req, res) => {
  const { name, email, password } = req.body;
  if (!email || !password || !name) {
    res.status(422).send({ error: "Please add all the fields" });
  }
  console.log(req.body);
  await User.findOne({ email: email })
    .then((savedUser) => {
      if (savedUser) {
// you need to add return to stop the code
       return res.status(422).send({ error: "Email already been used" });
      }
// or you can add else because the code keep running
      bcrypt.hash(password, 12).then((hashedpassword) => {
        const user = await User.create({
          name,
          email,
          password: hashedpassword,
        });

        user
          .save()
          .then((user) => {
            res.json({ message: "Sign Up Successfully" });
          })
          .catch((err) => {
            console.log(err);
          });
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

I think it is better to use something like throw new Error('Email already been used') instead of return for your res.status(422).send({ error: "Email already been used" }); because if you have return the server doesn't give back an error, but a normal answer, but of course it is ok if you want that.

Kevin
  • 85
  • 7
  • Thanks for your help. Unfortunately it didn't work. It is just keep pending when I post the data through front-end. I tested the api through postman and I got the respond instantly. So maybe something I did wrong on the front-end part? – Harris Ho Dec 07 '22 at 01:39
  • In this case, try to add `async` and `await` before axios call, for the same reason as before. Because, what I think may happen is, the `setEmail(""); setName(""); setPassword("")` are being called before axios. – Kevin Dec 07 '22 at 08:22
  • And just in case if is any error with the proxy set-up, test it like this : `await axios .post("http://localhost:5000/signup", newUserData).then((res) => console.log(res.data)).catch((error)=>console.log(error));` – Kevin Dec 07 '22 at 08:29
  • It didn't help after I added `async` and `await`. I even removed `setEmail(""); setName(""); setPassword("")` and it still remain the same pending status. I took your suggestion on proxy set-up texting, and it showed an error `POST http://localhost:5000/signup 422 (Unprocessable Entity)`. What should I do to fix it. – Harris Ho Dec 07 '22 at 20:01
  • I haven't seen `422 (Unprocessable Entity)` again... So, I posted a new answer, please if you can, try it and tell me the results. – Kevin Dec 08 '22 at 09:17
0

I want you to be sure that before you submit, the values name, email, password, are updated. Please try:

  const handleSubmit = async (event) => {
    // prevent page refresh
    event.preventDefault();
    console.log(`The value for the name: ${name}`);
    console.log(`The value for the email: ${email}`);
    console.log(`The value for the password: ${password}`);

    try {
      const response = await axios.post("http://localhost:5000/signup", {
        name,
        email,
        password,
      });
      console.log(response.data);
      setEmail("");
      setName("");
      setPassword("");
      console.log("form submitted ✅");
    } catch (error) {
      console.log(error);
    }
  };
Kevin
  • 85
  • 7
  • Case 1: I didn't input any name, email or password Case 2: I input all the field but the email is already been used Case 3: I input all the field and the email has not been used In the console, `name, email, password` are all updated in all 3 cases. I got `POST http://localhost:5000/signup 422 (Unprocessable Entity)` in case 1 and 2, which is the expected result based on my backend. For case 3 I successfully registered, which is also the expected result. – Harris Ho Dec 09 '22 at 09:01
  • However I got 2 respond in all 3 cases. Besides the expected responds (status 422 for case 1 and 2, status 200 for case 3), I got an extra respond status 204 no content for all 3 cases. Is it normal to have this status 204 respond? – Harris Ho Dec 09 '22 at 09:01
  • Besides the extra respond, it seems that it is working if I post data using the link `http://localhost:5000/signup` directly and without setting the proxy. If I post data using `/signup` and I set `"proxy": "http://localhost:5000",` in `package.json`, the result is always pending. Is there any way that I can set up the proxy correctly so I can use `/signup` to post data. – Harris Ho Dec 09 '22 at 09:07
  • About the 2 responses, as I told you in my first comment, you need to add `return` in your back end code, because the code keeps running. My opinion is instead of `return` add `throw` in your back end. Now, I'm not sure what's going wrong in your proxy's setup, you can have a look here [link](https://stackoverflow.com/questions/48291950/proxy-not-working-for-react-and-node) – Kevin Dec 11 '22 at 15:07
  • The response 204 means that _the request has succeeded, but that the client doesn't need to navigate away from its current page_, and you shouldn't have it, so check in your back end all cases you send a response. – Kevin Dec 11 '22 at 15:15
0

Change localhost to 127.0.0. for node 17 or higher

I hade the same problem working with Node>=17. It had worked with 16.

For me changing localhost to 127.0.0.1 worked.

juergi
  • 1,333
  • 1
  • 9
  • 16