express.js retrieve username from mysql database doesn't redirect to signin page

node js user authentication using mysql and express js
how to fetch data from database in node js and display in html
node.js express login example
creating registration and login form in node.js and mysql github
express js passport authentication mysql
node.js mysql select query example
node js login and registration
node js express mysql rest api authentication

I'm trying to retrieve username from mysql database, the below code can successfully retrieve the username. However, when err occurs, code doesn't redirect to /signin. The page redirect to /admin instead. Though, if I add

res.redirect('/signin')

just before the last curly bracket, it will redirect to the signin page, but it won't able to retrieve the username.

I want it to redirect to signin page, how?

const connection = require('./connection')

const signin = (req, res) => {

    var email = req.body.email
    var password = req.body.password
    let queryStr = `select username from users where email='${email}' and password='${password}'`

    return connection.query(queryStr, (err, rows, fields) => {
        if (err) {
            res.redirect('/signin')
                     
        } else {
            req.session.email = email
            res.json(rows[0])
        }
    })
    
}

module.exports = signin

Actually, You're Query is correct, But query doesn't return any rows. So if user not found on username table. It needs to signin page(This is your question correct?), For that you have to update the code like following,

const connection = require('./connection')

const signin = (req, res) => {

    var email = req.body.email;
    var password = req.body.password;
    let queryStr = `select username from users where email='${email}' and password='${password}'`;

    return connection.query(queryStr, (err, rows, fields) => {
        if (err) {
            res.redirect('/signin');           
        } else if(!rows.length) {
            res.redirect('/signin');
        }else {
            req.session.email = email;
            res.json(rows[0]);
        }
    })

}

module.exports = signin

Node js User Authentication using MySQL and Express JS, We will authenticate user using MySQL database.We will create GET and POST type HTTP request to show login and post login app.php: This file will use to create nodejs application server and routes url. req.session.user = results[0];// set user name Because mysql cant store files of different formats. The first step to recover deleted data from a MySQL database. Despite the fact that backing up doesn’t save much, it’s worth starting MySQL recovery as soon as possible. After all, this is the simplest and most free method, and not using it would be stupid. To prevent any data from being damaged, first, place it on a new server.

It looks your code is being executed after you have returned it. You can use promisified version of the same code.

use mysql-promise. this is promisified wrapper around the same library you are using. then Your code will look something like this:

// install mysql-promise

npm i mysql-promise

connection.js

const mysql = require("mysql-promise");

async function getDBConn() {
  const connection =  mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "root",
    database: "essencejoin"
  });
  await connection.connect();
  return connection;
}

module.exports = getDBConn;

then use it like this:

//signin.js

const signin = (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  const connection = getDBConn();
  let queryStr = `select username from users where email='${email}' and password='${password}'`;
  try {
    await connection.query(queryStr);
    req.session.email = email;
    res.json(rows[0]);
  } catch (error) {
    console.log(error);
    res.redirect("/signin");
  }
};

module.exports = signin;

disclaimer: I have not tested this, even if this does not work this should give you a fair idea how to make it work

Basic Login System with Node.js, Express, and MySQL, Sending and receiving data from the client using Node and Express. Unlike PHP, Node.js does not require Apache or Nginx, Node.js is its own the bodyParser package will extract the form data from our login.html file. The mysql module has the very useful PoolCluster feature, which can take the configurations for several instances and then connect to all of them. Let’s see how your db.js file will look: var mysql = require (' mysql '), async = require (' async ') var PRODUCTION_DB = ' app_prod_database ', TEST_DB = ' app_test_database ' exports. MODE_TEST

Without knowing too much about your project, I think you want to look into adding a status code with the express redirect.

 index(req, res, next) {
    topicQueries.getAllTopics((err, topics) => {
      if (err) {
        res.redirect(500, "static/index");
      } else {
        res.render("topics/index", { topics });
      }
    });
  }

Something like that. Also, look out for other simple mistakes in your project, that may cause this, that deal with Express.

https://expressjs.com/en/api.html#res.redirect

Using MySQL with Node.js and the mysql JavaScript Client, NoSQL databases are rather popular among Node developers, with MongoDB ( the way to get up and running with MySQL in Node, we've got you covered! Data returned from the MySQL database can be parsed by simply looping SQL as a result of not understanding how the ORM does what it does. In this article, we show how to retrieve data from a MySQL database using AJAX and PHP. Through AJAX, we can make asynchronous requests to the server to get information from the server such as in a database like a MYSQL database. This way, a user can keep on working while information in a page updates without the page having to be refreshed.

Querying Data in MySQL Database from a Node.js Program, In this tutorial, you will learn how to query data from a table in the MySQL database from a node.js application using the mysql module. For retrieve data from MySQL database using JSP first we have to create a table in data base. After create a table in the MySQL database you need to insert record or data on it.If you want to know how to insert data in jsp please visit the link : Insert data in JSP. The SELECT statement is used to retrieve data from one or more tables:

Handling user login and registration using nodejs and mysql, Nodejs has seen a dramatic increase in adoption in the backend Basically, I'm interested in how to pass user data from server to redirect. but there might be a need to use MySQL databases with nodejs until you "success":"Email and password does not match" sudo apt-get install mysql-workbench If you never set, forgot, or need to change your MySQL password, you're in luck. This article walks you through these steps, so you'll never be at a loss for that database root user password.

Node.js MySQL Select From, To select data from a table in MySQL, use the "SELECT" statement. Example. Select all records from the "customers" table, and display the result object: var mysql� Hello Friends, I am creating a simple Ajax application for database query and I've an servlet that connects to specified database and retrieve details for the specified key. I don't think there is anything wrong with the code, servlet is retrieving the parameters passed to it, it is able to connect to database, but can't retrieve details from

Comments
  • The backtick (`) in your query, is that a typo?
  • no, it's template literal
  • Make sure that err is coming back as true as well. If err is not true, your IF statement will never run. So ensure the callback function satisfies this.
  • I tried to enter wrong password and username, however, the err doesn't do a thing, I tried to console.log(err) but nothing shows, just go straight to /admin page. I guess wrong info proves err is not true. Adding "res.redirect('/signin')" just before the last curly bracket will redirect to the /signin page but retrieving username no longer work. So I'm thinking is more aboiut logic of the code
  • Post your connection query function.
  • const mysql=require('mysql') var connection=mysql.createConnection({ host:'localhost', user:'root', password:'root', database:'essencejoin', }) connection.connect() connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) { if (err) throw err console.log('The solution is: ', rows[0].solution) }) module.exports=connection