Post request with strange behavior

I have a node / express server set up, which is communicating with a mysql database (both of which are hosted on AWS, in elastic beanstalk environment and RDS instance respectively). I have created a simple create account authentication project in react, which I am currently running locally. I communicate to the server with a post request.

createAccount = (event) => {
  console.log("hello from createAccount");
  const isValid = this.validate();
  if (!isValid) {
    console.log("not valid");
    return false;
  } else {
    const formData = new FormData();
    formData.append("firstName", this.state.firstName);
    formData.append("lastName", this.state.lastName);
    formData.append("username", this.state.username);
    formData.append("passcode", this.state.passcode);
    console.log(formData);

    fetch("https://www.myurl.com/createUser", {
      method: "POST",
      headers: new Headers({
        "Access-Control-Allow-Origin": "*",
      }),
      body: formData,
    });
  }
};

And here is the server side code:

var mysqlConnection = mysql.createConnection({
  host: "my-endpoint",
  user: "****",
  password: "****",
  port: "****",
  database: "****",
});

app.post("/createUser", function (request, response) {
  console.log("/createUser");
  console.log(request.body);
  const createUser = `CALL CreateUser('${request.body.firstName}', '${request.body.lastName}', '${request.body.username}', '${request.body.passcode}')`;
  mysqlConnection.query(createUser, (error, result) => {
    if (error) {
      console.log(error);
    } else {
      console.log("SUCCESSFULLY CREATED A USER ACCOUNT");
      response.set("Access-Control-Allow-Origin", "*");
      mysqlConnection.end();
    }
  });
});

However, my post request is doing something strange…about 2/3 of the time, all goes as expected. The user creates an account and the information is successfully added to my database. However, the rest of the time everything seems to run fine (through examination of my console.log check points), but the information is not added to my database…the user does not successfully create an account. When this happens, I open up the logs from AWS to examine what the server is doing, and nothing is printed that I would expect. My new account information is not printed (while is usually is), and there is not an error printed either. This is a head scratcher. Is there some reason my post requests would not reach my server, BUT only part of the time? I am at a loss…

I ran the application totally in my local environment (changed my request to my local server as opposed to the one hosted on elastic beanstalk). This worked 100% of the time (please note that this is the same exact server code). I am perplexed as to this behavior, which is apparently something to do with the hosted version on elastic beanstalk in AWS. What is causing this behavior, and how can I fix it?

I switched back to the hosted server for further testing. I was just spam creating accounts to see if I could notice any patterns. The application creates a successful account about 1 in every 5 times. The other four times it will not save any info to the database. It is not a problem with my field data (I have implemented a little error checking), because I just spam the same info over and over until it finally creates. It eventually does, but only after about 4 tries.

Below is my post request with the added connection.end(), as well as where I initially connection to my database as requested in the comments.

var mysqlConnection = mysql.createConnection({
  host: "my-endpoint",
  user: "****",
  password: "****",
  port: "****",
  database: "****",
});

app.post("/createUser", function (request, response) {
  console.log("/createUser");
  console.log(request.body);
  const createUser = `CALL CreateUser('${request.body.firstName}', '${request.body.lastName}', '${request.body.username}', '${request.body.passcode}')`;
  mysqlConnection.query(createUser, (error, result) => {
    if (error) {
      console.log(error);
    } else {
      console.log("SUCCESSFULLY CREATED A USER ACCOUNT");
      response.set("Access-Control-Allow-Origin", "*");
      mysqlConnection.end();
    }
  });
});

Answer

The fetch Function returns a promise. Therefore you need to add a .then block. If you don’t use .then The code following will not be waiting for the fetch to be completed. Please check and let me know.

What’s a promise? A promise is resolved eventually and return a value unlike a synchronous function where the value is returned immediately.

fetch('https://www.myurl.com/createUser', {
    method: 'POST',
    headers: new Headers({
        'Access-Control-Allow-Origin': '*'
    }),
    body: formData
}).then(() => {
    Console.log(‘done’)

})

The second issue I see is that your server side express endpoint /createUser Should only be completed once the mysql query is completed. Therefore you should call res.end To end the request after the query is completed. So that the frontend will get the response from the api after the queries are completed.

mysqlConnection.query(createUser, (error, result) => {
    if (error) {
        console.log(error);
        res.status(400).send(new Error('error result'));

    } else {
        console.log('created user');
        res.send('success result')
    }
})

Leave a Reply

Your email address will not be published. Required fields are marked *