简体   繁体   English

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

[英]Saving user information in MySql with NodeJs

I want to make a register form. 我想做一个注册表。 After the "Submit" button is pressed the script opens my MySql database and inserts a new row in the "Users" table. 按下“提交”按钮后,脚本将打开MySql数据库,并在“用户”表中插入新行。 Everything works, except the browser can't interpret the NodeJs require function. 一切正常,除了浏览器无法解释NodeJs require函数。 Some other posts said to use browserify but I want to know if this can be done without other programs. 其他一些帖子说使用browserify,但我想知道如果没有其他程序就可以完成此操作。

My code: 我的代码:

register.html 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 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 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");
    }
}

You can't connect to your MySQL database directly from the browser. 您不能直接从浏览器连接到MySQL数据库。 Node is a separate enviroment to the Javascript interpreter in the browser, it runs in the server, and it is there that you should connect to the database. Node是浏览器中Javascript解释器的独立环境,它在服务器中运行,并且应该在此处连接数据库。 It is fairly easy to create an HTTP server with node: 使用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);
});

You would have, however, to handle routing ( ie executing different operations according to the path requested in the URL) directly by hand, so I'd recommend you to read about some Web framework for Node, like Expressjs⁽¹⁾ for instance. 但是,您将不得不直接手工处理路由( 根据URL中请求的路径执行不同的操作),因此,我建议您阅读有关Node的某些Web框架,例如Expressjs。

In Express you could do something like: 在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!')
});

Which would give you https://localhost:3000/hello and https://localhost:3000/world , one returning “Hello” and the other returning “World.” 这将为您提供https://localhost:3000/hellohttps://localhost:3000/world ,一个返回“ Hello”,另一个返回“ World”。

As for the communication between the browser and the server, you may use AJAX. 至于浏览器和服务器之间的通信,可以使用AJAX。 I would recommend you to use fetch,⁽²⁾ but you can use jQuery.ajax ⁽³⁾ also, or really any other solution, or even directly call the browser's XMLHttpRequest .⁽⁴⁾ 我建议您使用fetch,⁽,但是您也可以使用jQuery.ajax (或其他任何解决方案),甚至可以直接调用浏览器的XMLHttpRequest

⁽¹⁾ https://expressjs.com ⁾https //expressjs.com

⁽²⁾ Fetch is a new standard for web requests in the browser, which you can already use through this polyfill: https://github.com/github/fetch ⁾Fetch是用于浏览器中Web请求的新标准,您可以通过以下polyfill使用它: https : //github.com/github/fetch

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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