【问题标题】:HTML5 page logging with MySql database in Node.js with socket.io使用 socket.io 在 Node.js 中使用 MySql 数据库进行 HTML5 页面日志记录
【发布时间】:2012-06-04 19:50:51
【问题描述】:

我尝试使用 HTML5+MySQL+Node.js+socket.io 登录数据库,但失败了。请帮忙。 我想使用 Node.js 和 socket.io 从 HTML5 页面登录到 MySQL 数据库

我有一个带有 2 个文本框用户名和密码以及一个登录按钮的 HTML5 页面。 用户想从 HTML5 页面登录,用户/密码发送到服务器,服务器接收用户/密码并使用 mysql 数据库验证并返回结果。

我的代码: server_test.js

var io = require('C:/Program Files (x86)/nodejs/node_modules/socket.io/lib/socket.io');
var socket = io.listen(8124);
socket.sockets.on('connection',function(socket){
    socket.on('login', function(data, usr, pass){
        var mysql = require('mysql');
        var TEST_DATABASE = 'employee';
        var TEST_TABLE = 'tblusers';
        var client = mysql.createClient({
          user: 'root',
          password: 'secret10',
        });

        client.query('USE '+TEST_DATABASE);

        client.query(
          'SELECT name FROM '+TEST_TABLE+' WHERE user = '+usr+' AND password = '+pass,
          function selectCb(err, results) {
            if (err) {
              throw err;
            }
            //Emit a message to client
            socket.emit('retuLogIn',{username: results[0]['name']});
            client.end();
          }
        );
    });
        socket.on('disconnect', function(){
            console.log('Server has disconnected');
        });
});

client_test.html

<!doctype html>
<html>
    <title>WebSocket Client Demo [socket.io]</title>
    <script src="/json.js"></script> <!-- for ie -->
    <script src="http://localhost:8124/socket.io/socket.io.js"></script>
    <script>
    function connect() {

        try
        {
            var socket = io.connect('http://localhost:8124/');
            socket.on("connect",function(){
                document.getElementById('status').innerHTML ="Browser has connected to the app server";
            });
            socket.on('login', function (data, document.getElementById('txtUser').value, document.getElementById('txtPass').value) {
                //alert(data.hello);
                document.getElementById('status').innerHTML = 'Welcome '+data.username;
            });
        }
        catch(err)
        {
            document.getElementById('status').innerHTML = err.message;
        }
    }
    </script>
    <body>
        <h1>WebSocket Client Demo</h1>
        <div><p id="status">Enter user and password to Log-In</p></div>
        <label>User :</label>
        <input id="txtUser" type="text" maxlength="10" />
        <label>Password :</label>
        <input id="txtPass" type="text" maxlength="10" />
        <button id="connect" onClick='connect()'/>Log-In</button>
    </body>
</html>

注意: 我尝试使用上述代码但没有成功。我试图使用socket.send('abcd','ab12')从客户端将用户名/密码发送到服务器。可以发送但无法在服务器中接收。

请帮我解决这个问题。我正在使用 MySQL 数据库。

作为更新,当我应用 Joel 的建议时,当我尝试在 Node.js 中运行 app.js 时仍然看到错误:

C:\Program Files (x86)\nodejs>node "C:\Program Files (x86)\nodejs\app.js"    info  - socket.io started

C:\Program Files (x86)\nodejs\app.js:6
    var client = mysql.createConnection({
                       ^ TypeError: Object #<Object> has no method 'createConnection'
    at Object.<anonymous> (C:\Program Files (x86)\nodejs\app.js:6:24)
    at Module._compile (module.js:449:26)
    at Object..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function._load (module.js:312:12)
    at module.js:487:10
    at EventEmitter._tickCallback (node.js:238:9)

C:\Program Files (x86)\nodejs>

现在这有什么问题?

【问题讨论】:

    标签: mysql html node.js socket.io


    【解决方案1】:

    我刚刚修复了脚本,因为我需要类似的东西,给你:

    app.js:

        var app = require('http').createServer(handler)
          , io = require('socket.io').listen(app)
          , fs = require('fs')
          , mysql = require('mysql')
    
        var client = mysql.createConnection({
                  host: 'localhost',
                  user: 'root',
                  password: '',
        });
    
        client.connect();
    
        app.listen(3232);
    
        function handler (req, res) {
          fs.readFile(__dirname + '/index.html',
          function (err, data) {
            if (err) {
              res.writeHead(500);
              return res.end('Error loading index.html');
            }
    
            res.writeHead(200);
            res.end(data);
          });
        }
    
        io.sockets.on('connection', function (socket) {
            socket.on('login', function(usr, pass){
                var TEST_DATABASE = 'mysqltest';
                var TEST_TABLE = 'users';
    
                client.query('USE '+TEST_DATABASE);
    
                client.query('SELECT name FROM '+TEST_TABLE+' WHERE user = "'+usr+'" AND password = "'+pass+'"', function(err, results) {
                  if (err) throw err;
                  console.log(results[0]); // [{1: 1}]
                  socket.emit('retuLogIn',results[0]['name']);
                });
    
            });
            socket.on('disconnect', function(){
                console.log('Server has disconnected');
            });
        });
    

    还有index.html:

    <html>
        <title>WebSocket Client Demo [socket.io]</title>
        <script src="http://localhost:3232/socket.io/socket.io.js"></script>
        <script>
        function connect() {
    
            try
            {
                var socket = io.connect('http://localhost:3232/');
                socket.on("connect",function(){
                    document.getElementById('status').innerHTML ="Browser has connected to the app server";
                    socket.emit('login', document.getElementById('txtUser').value, document.getElementById('txtPass').value);
    
                });
                socket.on('retuLogIn', function (data) {
                    document.getElementById('status').innerHTML = 'Welcome '+data;
                });
            }
            catch(err)
            {
                document.getElementById('status').innerHTML = err.message;
            }
        }
        </script>
        <body>
            <h1>WebSocket Client Demo</h1>
            <div><p id="status">Enter user and password to Log-In</p></div>
            <label>User :</label>
            <input id="txtUser" type="text" maxlength="10" />
            <label>Password :</label>
            <input id="txtPass" type="text" maxlength="10" />
            <button id="connect" onClick='connect()'/>Log-In</button>
        </body>
    </html>
    

    如果需要,您需要更改 mysql 数据库名称、用户名、密码和可能的端口等内容。

    我使用了 node.js、socket.io 和 node-mysql

    【讨论】:

    • 乔尔,我尝试了你的代码,但没有成功。你能看看我哪里错了吗?我收到如下错误:C:\Program Files (x86)\nodejs>node "C:\Program Files (x86)\nodejs\app.js" info - socket.io started C :\Program Files (x86)\nodejs\app.js:6 var client = mysql.createConnection({ ^ TypeError: Object # has no method 'createConnection' at Object. (C:\Program Files (x86)\nodejs\app .js:6:24) 在 Module._compile (module.js:449:26) 在 Object..js (module.js:467:10) 在 Module.load (module.js:356:32) 在 Function. _load (module.js:312:12) at module.js:487:10 at EventEmitter._tickCallback (node.js:238:9)
    【解决方案2】:

    Chandan Dey 你不见了

    mysql = require('mysql')
    

    在您的代码中, 干杯

    【讨论】:

      猜你喜欢
      • 2011-03-06
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多