Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty.

Below is the query I am attempting to execute:

con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
          con.on('error', function (err) {
            console.log('[MySQL ERROR]', err);
            res.json('Register Error: ', err);
          });
          res.json('Successful Sign Up!');
        })

Additionally, here is the complete code:

//Libraries
var crypto = require('crypto');
var uuid = require('uuid');
var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');

//connection with MySQL

var con = mysql.createConnection({
  host: "localhost",
  user: "user",
  password: "password",
  database: "database",
});

//Encrypting password

var genRandomString = function (length) {
  return crypto
    .randomBytes(Math.ceil(length / 2))
    .toString('hex')
    .slice(0, length);
};

var sha512 = function (password, salt) {
  var hash = crypto.createHmac('sha512', salt);
  hash.update(password);
  var value = hash.digest('hex');
  return {
    salt: salt,
    passwordHash: value,
  };
};

function saltHashPassword(userPassword) {
  var salt = genRandomString(16);
  var passwordData = sha512(userPassword, salt);
  return passwordData;
}

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//Sign up
app.post('/register/', (req, res, next) => {
  var post_data = req.body;

  var uid = uuid.v4();
  var plaint_password = post_data.password;
  var hash_data = saltHashPassword(plaint_password);
  var password = hash_data.passwordHash;
  var salt = hash_data.salt;

  var email = post_data.email;

  con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
    con.on('error', function (err) {
      console.log('[MySQL ERROR]', err);
    });
    if (result && result.length) 
        res.json('User already exists');
    else
    {
      con.query("INSERT INTO user (unique_id, email, encrypted_password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
          con.on('error', function (err) {
            console.log('[MySQL ERROR]', err);
            res.json('Register Error: ', err);
          });
          res.json('Successful Sign Up!');
        })
    }
  });
})

//Login
app.post('/login/', (req, res, next) =>{

  var post_data = req.body;

  var user_password = post_data.password;
  var email = post_data.email;

  con.query("SELECT * FROM user where email=?", [email], function (err,result,fields) {
    con.on('error', function (err) {
      console.log('[MySQL ERROR]', err);
    });
    if (result && result.length) 
        {
          var salt = result[0].salt;
          var encrypted_password = result[0].encrypted_password;
          var hashed_password = checkHashPassword(user_password,salt).passwordHash;
          if(encrypted_password==hashed_password)
          res.end(JSON.stringify(result[0]))
          else
          res.end(JSON.stringify('Wrong Credentials'))
        }
    else
    {
      res.json('Wrong Credentials')
    }
  });

})

app.listen(3000, () => {
  console.log("RESTFul API running on port 3000");
});

Answer №1

Give this a shot and inform me of the outcome

con.query("INSERT INTO users (id, email, password, salt, created_at, updated_at) VALUES (?,?,?,?,NOW(),NOW())",[uid, email, password, salt], function (err, result, fields) {
              if(err) {
                console.log('[MySQL ERROR]',err);
                res.json('Registration Error: ',err);
              }else {

              res.json('Sign Up Successful!');
              }
          })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

Leveraging an external script for enhanced functionality in React/Meteor application

I'm currently facing a challenge incorporating an external script into my React component within Meteor. I've experimented with directly placing the script tag in my component as follows: TheLounge = React.createClass({ render() { return ( ...

Received a 'PDOException' error stating 'SQLSTATE[HY000] [2002] Connection timed out' while attempting to establish a connection with Google Cloud SQL

Hello everyone, I have been attempting to establish a connection with Google Cloud SQL from an external website. I have authorized the server's IP in Google Cloud under Instance -> Access Control -> Authorization The instance has been assigned an ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

What is the best approach for managing authentication across different frameworks?

My Ruby web applications utilize OpenID for authentication and save session information in a cookie. To address some limitations with API and AJAX functionality within my Ruby frameworks, I have integrated node.js services into the mix. The concern arises ...

Utilizing destructuring and Object.entries for advanced formatting

I'm embarking on a new React project and facing an issue with the JSON data structure returned by my API for meetings. I attempted to utilize destructuring and Object.entries. This is what I currently have: { "meetings": [ ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

What is the method to have VIM recognize backticks as quotes?

Currently working in TypeScript, I am hoping to utilize commands such as ciq for modifying the inner content of a template literal. However, it appears that the q component of the command only recognizes single and double quotation marks as acceptable ch ...

Why does Angular-CLI remove an old module when installing a new module using npm?

After adding the ng-sidebar module to my app, I decided to install a new module called ng2-d&d: npm install ng2-dnd --save However, after installing the new module, the old ng-sidebar module was removed from the app-module and an error occurred: C ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

Adding a JSON array to HTML using JavaScript

Looking to incorporate JSON Array data into an HTML list with Headings/Subheadings using JavaScript. I experimented with two methods - one involving jQuery and the other mostly vanilla JS. The initial attempt (link here: http://jsfiddle.net/myu3jwcn/6/) b ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...

Issues with displaying images have been encountered with the Chessboardjs NPM package

Currently, I am attempting to utilize the https://www.npmjs.com/package/chessboardjs package in conjunction with meteor 1.13. Despite developing a simple react component to display the board, the images are not rendering as expected. Below is the code for ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

What is the maximum number of promises that can be handled by Promise.all?

Just the other day, I encountered an error while trying to resolve a significant amount of promises: Error: Promise.all received too many elements I searched through MDN and ECMA-262 but couldn't find any resources outlining limits for this. ...

Is there a way to customize the color of the HR element in a Material-UI Select Field?

https://i.stack.imgur.com/DYeX7.png https://i.stack.imgur.com/CN0T6.png Hi there, I am currently working on a website and using a Select Field component from Material-UI. I am faced with the challenge of customizing the style to change the default light ...

Error occurred due to a response timeout when attempting to retrieve http://registry.npmjs.org/@typescript-eslint%2feslint-plugin after 30 seconds

The current NPM version I am using is 6.14.4. While attempting to create a react application with 'npx create-react-app helloapp', an error occurred indicating that the data could not be fetched. The specific error message received was: npm ERR ...

Issues encountered when selecting table data for filtering

One issue I am facing is with my HTML table that contains a lot of data. I have created a select option to filter the table and display the filtered data. The select options are based on the "route" column, with only three options available: Marikina, Mont ...

In Angular, link a freshly loaded ".js" controller to a newly loaded "html" view following the bootstrapping process on ngRoutes

As a newcomer to Angular, I have been experimenting with loading dynamic views using ngRoutes (which is very cool) along with their respective .js controllers for added functionality. However, I am encountering difficulties in binding them together after b ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...