0

I am new to nodeJS and I have been trying to create a registration form with validation.

The validation part is complete with sql query statements, but I am having trouble redirecting from my server side back to registration form with a message info such as 'Email address already exists'.

How do I process this on the client 'register.js' ?

register.js

      <form id='register-form' method="POST"  action="http://localhost:3306/register">

server.js

app.post('/register', (req,res) => {  
var email = req.body.email;
var password = req.body.password;

let sql = "SELECT * FROM user WHERE email='" + email + "'";

db.query(sql,(err,result) => {
if (err) throw err;

if (result.length > 0) {
  console.log("user already exists");
  res.redirect('http://localhost:3000/#/Register');
} else {
  insertUser(email,password);
  res.send(email + " has been added to database");
}

1 Answers1

0

There are mutliple queries...

  • I am not sure if your register.html file is within any folder(say, public) that is publicly accessed by using express static middleware. If yes, I hope you are setting the static middleware

app.use(express.static('public'));

  • Do you want to send a response as Bad Request if email id is already present in DB?, then please try below
    if(!result.length)
    res.status(400).json('Email Id Already exists');

OR

res.status(400).send(400, {error:'Email Id Already exists'});

  • You need a body-parser to parse the URL encoded notation..sample code which worked for me:

    let express=require('express');
    let app = express();
    let server = require('http').createServer(app);
    
    var bodyParser = require('body-parser');
    var parseUrlencoded = bodyParser.urlencoded({ extended: false });
    
    app.use(express.static('public'));
    
    
    app.post('/register', parseUrlencoded, (req,res) => {
        var email = req.body.email;
        var password = req.body.password;
          if (!email) {
            res.writeHead(404,
                 {Location: 'http://localhost:3306/register.html'}
             );
            res.end();
           }
           else{
              res.status(200).json('email is not empty');
            }
    });
    server.listen(3306, ()=> console.log('app started'));
    

Some examples: Proper way to set response status and JSON content in a REST API made with nodejs and express

Error: Can't set headers after they are sent to the client

Work
  • 73
  • 1
  • 9
  • yup, so 1 query checks if the email exists or not in the db and the other query insertUser(email,password) is for the SQL statement 'INSERT ....' I basically want to redirect back to my register form with a message displaying 'Email already exists' like in any generic form registration. My register form is not in a pubilic folder, rather I created a route for it using react routers – Cliff Yuen Jan 15 '18 at 15:07