Home > Software design >  Login system React JS
Login system React JS

Time:10-10

That's my code for backend of my app, creating account working very well but i dont know how to implement login system. Can someone help me? app.post(/login) <- here it starts I have idea how it'll be works but i don't know how to do it. My idea is, get username and password from inputs, check if that exist in database, if it is go to dashboard, if not show error.

const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors')

app.use(cors())
app.use(express.json())

const db = mysql.createConnection({
    user: 'root',
    host: 'localhost',
    password: 'my_password',
    database: 'myplan_database'
});

app.post('/create', (req, res) => {

    const username = req.body.username
    const mail = req.body.mail
    const password = req.body.password

    db.query(
        'INSERT INTO users (username, mail, password) VALUES (?, ?, ?)', 
        [username, mail, password], (err, result) => {
            if (err) {
                console.log(err)
            } else {
                res.send('Values Insterted')
            }
        }
    );
});

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

    const username = res.db.username
    const password = res.db.password

    db.query(
        
    );
});

app.listen(3001, () => {
    console.log('Server is running')
})

CodePudding user response:

You can check the below code. Hope this code snippet will help you.

app.post("/login", (req, res) => {
  // Capture the input fields
  const username = req.body.username;
  const password = req.body.password;
  // Ensure the input fields exists and are not empty
  if (username && password) {
    // Execute SQL query that'll select the account from the database based on the specified username and password
    db.query(
      "SELECT * FROM users WHERE username = ? AND password = ?",
      [username, password],
      function (error, results, fields) {
        // If there is an issue with the query, output the error
        if (error) throw error;
        // If the account exists
        if (results.length > 0) {
          // Authenticate the user
          req.session.loggedin = true;
          req.session.username = username;
          // Redirect to home page
          res.redirect("/dashboard");
        } else {
          res.send("Incorrect Username and/or Password!");
        }
        res.end();
      }
    );
  } else {
    res.send("Please enter Username and Password!");
    res.end();
  }
});

  • Related