使用NodeJs在MySql中保存用户信息

时间:2017-04-10 16:26:07

标签: javascript html mysql node.js web

我想要一个注册表格。在"提交"按下按钮脚本打开我的MySql数据库并在"用户"中插入一个新行。表。 一切正常,除了浏览器无法解释NodeJ require功能。 其他一些帖子说使用browserify,但我想知道是否可以在没有其他程序的情况下完成。

我的代码:

register.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script src = "index.js" type="text/javascript"></script>
<script src = "register.js" type = "text/javascript"></script>

<link rel="stylesheet" type="text/css" href = "register.css">
</head>

<body>
<form name = "registerForm" method = "post">
<p id = "fillRule">Username must contain lower or uppercase or _! Fill in all boxes except the job! Pass must contain small and uppercase letters and its lenght must be at least 6 char, max 10!</p>
<label for="username">Username:</label>
<input type = "text" id = "username" name = "username" onchange = "checkUser()"> <br/>
<label for="firstname">Firstname:</label>
<input type = "text" id = "firstname" name = "firstame" onchange = "checkFirst()"> <br/>
<label for="lastname">Lastname:</label>
<input type = "text" id = "lastname" name = "lastname" onchange = "checkLast()"> <br/>
<label for="job">Your job:</label>
<input type = "text" id = "job" name = "job" onchange="checkJob()"> <br/>
<label for="pass">Password:</label>
<input type = "text" id = "pass" name = "pass" onchange = "checkPass()">        <br/>
<label for="mail">E-mail:</label>
<input type = "email" id = "mail" name = "mail" onchange = "checkMail()"> <br/>
<input type = "button" value = "send" id = "gomb" disabled = "disabled"   onclick = "registerButtonClick()">
</form>
</body>

</html>

index.js

    //export {addUser};

    // String formatting
    if (!String.format) {
    String.format = function(format) {
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/{(\d+)}/g, function(match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match
                ;
        });
    };
}
//

var mysql = require("mysql");

function createConnection(hostName, userName, passwd, db)
{
    const con = mysql.createConnection({
        host: hostName,
        user: userName,
        password: passwd,
        database: db
    });
    return con;
}

 function openConnection(con)
{
    con.connect(function (err) {
        if (err) {
            console.log('Error connecting to Db');
            return;
        }
        console.log('Connection established');
    });
}

function executeFullSelect(con, tableName)
{
    const statement = "SELECT * FROM " + tableName + ";";
    con.query(statement, function(err, rows)
    {
        if (err)
        {
            throw err;
        }
        console.log("Data received from " + tableName + ".\n");
        console.log(rows);
        /*for (var i = 0; i < rows.length; i++)
        {
            console.log(rows[i].UserName);
        }*/
    });
}

function insert(con, userName,firstName, lastName, job, mail, passwd)
{
    const statement = String.format("call newUser(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\", \"{5}\");", userName, firstName, lastName, job, mail, passwd);
    con.query(statement, function(err, rows)
    {
        if (err)
        {
            console.log("Error at insert");
            return 0;
        }

        console.log(userName + " was successfully added:)");
        return 1;
    })
}

function closeConnection(con)
{
    con.end(function (err) {});
}

function addUser(userName, firstName, lastName, job, mail ,passwd)
{
    const con = createConnection("localhost", "root", "micimacko", "users");
    openConnection(con);
    if (!insert(con, userName, firstName, lastName, job, mail ,passwd))
    {
        closeConnection(con);
        return 0;
    }
    closeConnection(con);
    return 1;
}

register.js

function registerButtonClick()
{
    const userName = document.forms["registerForm"]["username"].value;
    const firstName = document.forms["registerForm"]["firstname"].value;
    const lastName = document.forms["registerForm"]["lastname"].value;
    const job = document.forms["registerForm"]["job"].value;
    const mail = document.forms["registerForm"]["mail"].value;
    const pass = document.forms["registerForm"]["pass"].value;

    if (addUser(userName, firstName, lastName, job, mail, pass))
    {
        alert("added");
    }
    else
    {
        alert("failed");
    }
}

1 个答案:

答案 0 :(得分:0)

您无法直接从浏览器连接到MySQL数据库。 Node是浏览器中Javascript解释器的独立环境,它在服务器中运行,您应该连接到数据库。使用node:

创建HTTP服务器相当容易
var http = require('http');
var port = 3000;

const requestHandler = function (request, response) {  
 console.log(request.url)
 response.end('Hello Node.js Server!');
};

const server = http.createServer(requestHandler);

server.listen(port, function (err) {  
  if (err) {
    return console.log('something bad happened', err)
  }
  console.log('server is listening on ' + port);
});

然而,您可以直接手动处理路由(根据URL中请求的路径执行不同的操作), 所以我建议你阅读一些Node的Web框架,例如Expressjs⁽¹。

在Express中,您可以执行以下操作:

var express = require('express');
var app = express();

app.get('/hello', function (req, res) {
  res.send('Hello');
});

app.get('/world', function (req, res) {
  res.send('World');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
});

哪个会给你https://localhost:3000/hellohttps://localhost:3000/world,一个返回“你好”而另一个返回“世界”。

对于浏览器和服务器之间的通信,您可以使用AJAX。我建议你使用fetch,⁽²⁾但是你也可以使用jQuery.ajax⁽³,或者任何其他解决方案,甚至可以直接调用浏览器的XMLHttpRequest。⁽⁴⁾

⁽¹⁾https://expressjs.com

⁽²⁾Fetch是浏览器中Web请求的新标准,您可以通过此polyfill使用它:https://github.com/github/fetch

⁽³⁾http://api.jquery.com/jquery.ajax/

⁽⁴⁾http://youmightnotneedjquery.com/#ajax