Verify the data provided by the client on the client side and cross-reference it with the data stored in mySql database on

Assistance is needed in comparing and validating data from client-side to server-side to determine the validity of an email. The process involves the client entering an email, clicking a verification button, which triggers a check on the server side to see if the email exists in the database. If the email exists, the user is deemed valid; otherwise, they are not allowed to proceed further. Issues have been encountered with implementing this functionality using Express and MySQL queries. Testing via Postman consistently returns 'valid'. Sample emails from the MySQL database:

https://i.sstatic.net/hltHZ.png

The JavaScript Express code utilizes the app.post command but seems to have errors causing incorrect condition checking and statement writing. When tested in Postman, it always returns 'valid', preventing authentication on the client side. Uncertainty persists regarding the conditions that should be implemented due to a lack of familiarity with Express.

app.post('/verifyEmail', (req, res) => {
  var email = req.body.email;
  let sql = 'SELECT * FROM email WHERE email = ?'; //incorrect condition checking
  let query = db.query(sql, (err, result) => {
    if (email == null || !email) { //incorrect condition checking
      throw err;
      res.send('invalid');
    }
    console.log('valid');
    res.send('valid');
  })
})

The front-end uses Angular with TypeScript for handling the email verification process.

//service.ts
email: string[];
getEmailAPI(): Observable < any > {
  return this.http.get("http://localhost:8000/verifyEmail")
    .map((res: Response) => res.json())
    .catch((error: any) => Observable.throw(error.json().error || 'Server error'))
}

//component.ts
Email = [];
isVerified: boolean;
getEmailAPI() {
  this.QuestionService.getEmailAPI().subscribe(
    data => console.log('All email', this.Email = data),
    error => console.log('server returns error')
  );
}

verifyEmail(formValue) {
  this.AppService.getEmailAPI().subscribe(
    data => {
      if (data) {
        // do whatever needed is with returned data
        this.isVerified = true;
      } else {
        this.isVerified = false;
      }
    },
    error => console.log('server returns error')
  );
}
<!--component.html-->
<form #emailVerification='ngForm' ngNativeValidate>
  <label>Please Enter Your Email Below</label>
  <input name="email" type="text" required/>
  <button type="submit" (click)="verifyEmail(emailVerification.value)">VERIFY</button>
</form>

Seeking assistance to resolve the issues mentioned above. Additional details can be provided upon request.

Answer №1

By validating whether the email variable is null, you can ensure that you will always receive a valid response. The end result should be returning JSON data, as your client expects to receive it in this format. Update your code as shown below:

 app.post('/verifyEmail', (req, res) => {
  var email = req.body.email;
  let sql = 'SELECT count(*) as count FROM email WHERE email = ?';
  let query = db.query(sql, [email],(err, result) => {
    if (result[0].count == 1) {
      res.json({
        "data": "valid"
      })
    } else {

      res.json({
        "data": "invalid"
      })

    }
  });
});

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

Here's a quick guide on incorporating query parameters into the router.get method

System: MEAN technology stack Hello, I'm trying to incorporate a query parameter into my router.get method and could use some guidance. The current setup looks like this: http://test.com/path1/path2/1 router.get('/path1/pa ...

Enhancing TypeScript modules - accessing the instance reference

While I have a good understanding of how module augmentation works, I am struggling to obtain the object reference in the new method's implementation. To provide an example, I aim to enhance the es2015 Map interface. In my code, I include: declare ...

What is the process for restarting the timer within a timer controlled by the react-countdown component?

Looking for guidance on how to implement a reset() function in ReactJS and JavaScript to reset a timer when the "Reset Clock" button is clicked on my webpage. The goal is to have the timer return to its initial value. Open to suggestions on how to achieve ...

ExpressJS with Sequelize is throwing an er_bad_field_error which indicates that there is an unknown column in the

When using the model file provided along with Sequelize, I am able to successfully run this code without any errors and perform an insert: var crypto = require('crypto'); module.exports = function(sequelize, DataTypes) { var User = sequelize.d ...

StopPropagation() method in Ng-class not functioning properly in Angular for parent element

I am facing an issue with 2 nested ng-repeats. The parent one is supposed to add a class based on ng-click, but even when I click the child, it still triggers when I don't want it to. <div class="add-filter-tags" data-filter="{{f1}}" ng-class="{&a ...

The resizing issue persists with Angularjs charts

I have recently developed a small web application using AngularJS and I have implemented two charts from the AngularJS library - a bar chart and a pie chart. Although both charts are rendering correctly, they are not resizing properly as the display size c ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

Execute a MySQL shell command using sed in Java

Hi everyone! I am currently facing an issue with running a shell command (mysql) in Java using getruntime. Here is the command I am trying to execute: sql=$(mysql -u cactiuser -ppassword cacti -s -N -e "select name_cache, name from data_template_data whe ...

It appears that the JavaScript global dynamic variable is undefined as it changes from function to function, suggesting it might be

I'm encountering an issue with the way these two functions interact when used in onclick calls of elements. Due to external circumstances beyond my control, I need to keep track of when and how elements are hidden. Everything works perfectly as inten ...

Utilize javascript to activate the hyperlink

Clicking the following link will open a video: <a href="<?php echo $rows['image1'] ; ?> " rel="vidbox" title="<?php echo $rows['name']." <br>".nl2br($rows['detail']) ; ?>" id="m2"><?php ...

Storing an array of strings in an SQLite table column using Sequelizers

Is there a way to store an array of strings in a column and perform queries using this column? I attempted to use the JSON data type for the column, but I also need to make [Op.like] queries on this JSON column. For example: { actors: { [Op.like]: `% ...

Search for the total number of rows in a table that have been selected within the last 30 days

Is there a way to retrieve and count the number of rows from the past 30 days without triggering any warnings? Here is my current code: $thirty_reg=mysql_query("SELECT * FROM user ORDER BY user.date DESC LIMIT 30"); $num_thirty=mysql_num_rows($thirty_reg ...

Execute a JavaScript function triggered by PHP validation and form submission

I have implemented PHP validation for a form where if a user forgets to enter a username, an error message is displayed. Instead of displaying a text error message, I want the input box to be highlighted in red using JavaScript. However, I am encountering ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

Show a message on form submission rather than redirecting

I'm working on a simple sign-up form and I want to show a success message directly on the page instead of redirecting to another page after submission. Is it better to display the message as a pop-up, an alert, or just on the page itself? <form a ...

Building an MVC structure using Node.js and Express with an already existing codebase

I have two files: one index.html and one server.js (codes below). Currently, they are functioning properly. However, I am aware of the importance of organizing code in an MVC architecture. I attempted to create a project from the ground up using Express on ...

Could someone please clarify why the data I input is not appearing in my hbs file?

I've been facing an issue where I am unable to send data from my main.js file to bookings.hbs file, although it works perfectly fine when sending the same data to index.hbs file. Can someone help me identify where the error might be occurring? App.js ...

What is the most efficient way to condense multiple repetitive case statements?

Within my code, I have multiple case statements that are quite similar, with the only difference being the argument 'key' from the function click(key). The variable 'c' is represented as JSON. The challenge lies in incorporating the ar ...

Are socket.io and websocket secure for integration with an express server?

I am interested in creating a real-time system using express and recently learned about socket.io and websockets. However, I have concerns about the security of using const io = socket.io("https://example.com");. Since the socket connection URL is accessib ...

I am encountering an issue while trying to update SQL data from within a Node.js

Using a for-loop to update SQL command is common practice. Here's an example: for(var i=count1; i < count2;i++){ Book.TimeStart = Times[I] console.log(Book.TimeStart) sql = sql + `UPDATE projectroom.Details SET BookingId = `+Book.Bo ...