Volkan Y
Volkan Y

Reputation: 149

NodeJS response to POST using Socket.IO

client (browser) POSTs values like username, password, email ... My NodeJS application receives them and now needs to first check if the username/email is already used in the database, and responses to client "Username is already taken" if so.

My problem is how do I tell the client within app.post() ?

app.post("/register", function(req,res){

Should I just use Socket.IO for everything and just avoid using POST (I thought POST was handy)?

Upvotes: 0

Views: 44

Answers (1)

julianwyz
julianwyz

Reputation: 3182

EDIT

My problem is I want the client to be triggered on a message like "Username is already taken" and just do a minor change on a label "Username taken" instead of writing the entire page new.

Ok, I think I see the issue you face.

Assuming you have a page on the client with a <form> such as this:

<form id="myform" action="/register" method="post">
  <label for="fname">First name:</label>
  <input type="text" name="fname"><br><br>
  <label for="lname">Last name:</label>
  <input type="text" name="lname"><br><br>
  <input type="submit" value="Submit">
</form>

When the user clicks the Submit button, their browser will send the POST request by redirecting the user's page.

If I understand correctly, you want to send this request without the user being redirected.

If this is indeed the case, I would use a fetch (or something similar) to do the job.

So on the client's page, you would do something like this:

First, add this prop to your form:

...
<form onsubmit="submitForm(event)">
...

Then add something like this script:

<script type="text/javascript">
async function submitForm(event) {
   event.preventDefault(); // This will keep the user from being redirected

  try {
    const username = getUsernameValue(); // get the value from the input or something

    // Fetch will send a POST request to /register without navigating the page
    const response = await fetch('/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      // The body is what will be in req.body on the server
      body: JSON.stringify({
        username: username
      })
    });

    const responseData = response.json();
    /*
      Assuming the server returns some structure like:
      {
         error: "Username is already taken"
      }
    */
    if (responseData.error && responseData.error === 'Username is already taken') {
      // Do something here
    } else {
      console.log("Everything is OK");
    }
  } catch(err) {
    console.error('something went wrong', err);
  }
}
</script>

Original Answer

Socket.IO (more broadly, Websockets) and POST (REST APIs) function differently and each can help solve different problems.

For the type of situation you outlined, I would continue to use a REST API.

I recommend reading up a bit on Express and how to send a response.

Here is some pseudo-code that will hopefully point you in the right direction:

app.post("/register", function(req,res){
  const { username, email, password } = req.body;

  if (!isUsernameUnique(username) || !isEmailUnique(email)) {
    return res.status(400).send('Username is already taken');
  }

  // Save in Database
  ...
  ...
  ...

  // Everything is good now
  res.send("Created user");
});

Upvotes: 1

Related Questions