简体   繁体   中英

Hey I don't know where to start when inserting data into MySql from html form using node.js

I just want to know where to start with getting my html page to work with my back end code and database. I want to insert information into my table with a basic html login page but all i found were confusing sources, maybe i suck at googling but was wondering if someone can help telling me where i should start and what else i need to learn in order to achieve this, The code below is what i managed to learn and implement.

var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var url = require('url');
var pages = require('html-pages');

const css = fs.readFileSync(`${__dirname}/public/art.css`, 'utf-8');
const htmlLogin = fs.readFileSync(`${__dirname}/login.html`, 'utf-8');
const htmlSignUp = fs.readFileSync(`${__dirname}/signup.html`, 'utf-8');


//static files for login
app.use('/login', express.static('./public'));

//
app.get('/login', function(req,res,next) {
    res.writeHead(200, {'Content-Type' :'text/html'});
    res.write(htmlLogin);

    next();
}).listen(3000);

app.get("/signup", function(req,res, next) {
    res.writeHead(200, {'Content-Type':'text/html'});
    res.write(htmlSignUp);

});

and here is my html page

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <link href="./signup.js">

</head>
  <body>
    <div class="signupBox">
        <h1 id="signUp">Sign Up!</h1>
        <div>
            <input text="text" placeholder="First Name" name="" value="">
        </div>
        <div>
            <input text=text" placeholder="Last Name" name="Last Name" value="">
        </div>
        <div>
            <input text="text" placeholder="Email" name="Email" value="">
        </div>
        <div>
            <input text="text" placeholder="Password" name="Password" value="">
        </div>
        <input id="submit" type="button" name="" value="Sign In">

    </div>
  </body>

  </html>

Learning how to back end with node.js and mysql just got stuck in knowing how to do this task,

var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var http = require('http');
var sql = require('mysql');
var fs = require('fs');
var url = require('url');

var myDB = sql.createConnection({
    //properties...
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'sampleDB'
    });

myDB.connect(function(err) {
    if (err) {
        console.log('There is an error');
    } else {
        console.log("Connected to Database");
    }
});

As what I am seeing from your code, you already setup login and signup page, it it's working than now you now to save signup data you can create new route like

app.post("/register", function(req,res, next) {
    console.log('request data', req.body) // you will get signup for data here.
});

and in signup for you need to add action like -

<form method="post" action="localhost:3000/register">
   <h1 id="signUp">Sign Up!</h1>
        <div>
            <input text="text" placeholder="First Name" name="" value="">
        </div>
        <div>
            <input text=text" placeholder="Last Name" name="Last Name" value="">
        </div>
        <div>
            <input text="text" placeholder="Email" name="Email" value="">
        </div>
        <div>
            <input text="text" placeholder="Password" name="Password" value="">
        </div>
        <input id="submit" type="button" name="" value="Sign In">
</form>

you can do same with login verification, send login detail as in below route -

app.post("/checkLogin", function(req,res, next) {
    console.log('request data', req.body) // you will get login detail here.
});

Hop this help.

Update html:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <link href="./signup.js">

</head>
  <body>
    <div class="signupBox">
        <h1 id="signUp">Sign Up!</h1>
        <form action="signup" method="POST">
        <!-- it's important to define name="xx" here otherwise you'll get 'undefined' value in server side -->
        <div> <input type="text" placeholder="First Name" name="firstname"> </div>
        <div> <input type="text" placeholder="Last Name" name="lastname"> </div>
        <div> <input type="text" placeholder="Email" name="email"> </div>
        <div> <input type="password" placeholder="Password" name="password"> </div>
        <input id="submit" type="button" name="" value="Sign Up">
        </form>
    </div>
  </body>
  </html>

Add this code in server side:

app.post ("/signup", function(req, res) {
        // get info from form
        var firstname = request.body.firstname;
        var lastname = request.body.lastname;
        var email = request.body.email;
        var password = request.body.password;
        var adduserquery = "INSERT INTO `myTable` (`firstname`,`lastname`,`email`,`password`) VALUES ('" + firstname + "', '" + lastname + "', '" + email + "', '" + password + "')";

        if (email) {
           // check if e-mail already exists
            myDB.query('SELECT * FROM `myTable` WHERE email = ?', [email], function(error, results, fields) {
                if (results.length > 0) {
                    response.send('This e-mail is already registered!' );
                } else {
                    // execute query to insert data
                    myDB.query(adduserquery, (err, result) => {
                    if (err) {
                        return response.status(500).send(err);
                    }
                    // if insert is successful, return you to homepage
                    response.redirect('/home');
                });
            }
        });
    }
}
}

Thats great you have already added the express module , i woud suggest try adding form tag and give the action to the form tag , on which you want to hit eg /signup and change your input type button to submit this will workout .

<div class="signupBox">
     <form action='/signup'>
        <h1 id="signUp">Sign Up!</h1>
        <div>
            <input text="text" placeholder="First Name" name="" value="">
        </div>
        <div>
            <input text=text" placeholder="Last Name" name="Last Name" value="">
        </div>
        <div>
            <input text="text" placeholder="Email" name="Email" value="">
        </div>
        <div>
            <input text="text" placeholder="Password" name="Password" value="">
        </div>
        <input id="submit" type="button" name="" value="Sign In">
     </form>
    </div>

Now if you click on submit the data can be getable inside the /signup route you have created using the req.body.NAME_VALE , once you got the value you can insert it into the database .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM