mysql - Node.js 套接字 io 'Error:Client is not defined'

标签 mysql node.js amazon-ec2 socket.io

我正在遵循教程并尝试使用 mysql 和 Ec2 实例创建一个简单的 node.js 服务器。问题是,我不断收到错误“node.js:201” 扔 e;//process.nextTick 错误,或第一个刻度上的“error”事件 ^ ReferenceError:客户端未定义 在对象。 (/var/www/app.js:28:3)'

我不知道为什么要这样做。我已将正确的文件加载到我的 index.html 中:

<!DOCTYPE html>

<html>
<head>
        <title></title>

        <script src="http://54.213.60.208:8080/socket.io/socket.io.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

</head>
<body>

        <script type="text/javascript">

        $(document).ready(function() {
  var socket  = io.connect('http://54.213.60.208:8080');

 $('#save').click(function() {
    if ($('#employee_name').val() == '' || $('#employee_salary').val() == '') {
      return alert('Please enter both name/salary!');
    }
    var data = {
      name: $('#employee_name').val(),
      salary: $('#employee_salary').val()
    };
    socket.emit('add employee', data);
    $('#employee_name').val('');
    $('#employee_salary').val('');
  });

 socket.on('populate', function(data) {
    var out = "";
    $.each(data, function(i, obj) {
      out += "<li>"+obj.name+" is making "+obj.salary+"</li>";
    });
    $('#employees').html(out);
  });
});

        </script>

<b>Create new employee</b>
<div>Name: <input id="employee_name" value="" type="text"></div>
<div>Salary: <input id="employee_salary" value="" type="text"></div>
<div><input value="Save" id="save" type="button"></div>

<br>
<b>List of Employees:</b>
<ul id="employees"></ul>

</body>
</html>

这是我的服务器代码:

var fs = require('fs');
var db_helper = require("./db_helper.js");

var app = require('http').createServer(function handler(req, res) {
  fs.readFile(__dirname + '/index.html', function(err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    } else {
      res.writeHead(200);
      res.end(data);
    }
  });
}).listen(8080);


var io = require('socket.io').listen(app);
io.sockets.on('connection', function(client) {
  console.log('Client connected');

  // populate employees on client
  db_helper.get_employees(function(employees) {
    client.emit('populate', employees);
  });
});

// client add new employee
  client.on('add employee', function(data) {
    // create employee, when its done repopulate employees on client
    db_helper.add_employee(data, function(lastId) {
      // repopulate employees on client
      db_helper.get_employees(function(employees) {
        client.emit('populate', employees);
      });
    });
});

最后,我的Mysql文件:

var mysql = require('mysql');
var MYSQL_USERNAME = 'root';
var MYSQL_PASSWORD = 'RMWpsu@13';

var client = mysql.createConnection({
  user: MYSQL_USERNAME,
  password: MYSQL_PASSWORD,
});

// destroy old db
client.query('DROP DATABASE IF EXISTS mynode_db', function(err) {
  if (err) { throw err; }
});

// create database
client.query('CREATE DATABASE mynode_db', function(err) {
  if (err) { throw err; }
});
console.log('database mynode_db is created.');
client.query('USE mynode_db');

// create table
var sql = ""+
"create table employees("+
" id int unsigned not null auto_increment,"+
" name varchar(50) not null default 'unknown',"+
" salary dec(10,2) not null default 100000.00,"+
" primary key (id)"+
");";
client.query(sql, function(err) {
  if (err) { throw err; }
});
console.log('table employees is created.');

// function to create employee
exports.add_employee = function(data, callback) {
 client.query("insert into employees (name, salary) values (?,?)", [data.name, data.salary], function(err, info) {
    // callback function returns last insert id
    callback(info.insertId);
    console.log('Employee '+data.name+' has salary '+data.salary);
  });
}

最佳答案

这个错误正是听起来的样子。 client 未定义,因为您在 io.sockets.on('connection', function(client) {) 之外进行了 client.on 调用> 函数。它需要在里面。

io.sockets.on('connection', function(client) {
  console.log('Client connected');

  // populate employees on client
  db_helper.get_employees(function(employees) {
    client.emit('populate', employees);
  });

  // client add new employee
  client.on('add employee', function(data) {
    // create employee, when its done repopulate employees on client
    db_helper.add_employee(data, function(lastId) {
      // repopulate employees on client
      db_helper.get_employees(function(employees) {
        client.emit('populate', employees);
      });
    });
  });
});

关于mysql - Node.js 套接字 io 'Error:Client is not defined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17815636/

相关文章:

Mysql:使用2列按降序对表进行排序

php - WordPress mysql 消失了

javascript - 无法修改已提交 FireStore 的 WriteBatch

javascript - 使 Discord 机器人命令不区分大小写?

amazon-web-services - AWS通过cloudformation启用EBS加密

mysql - 使用 JPA/Hibernate,如何将 Java 枚举映射到 MySQL 表中的列?

MySQL 限制解决方法

node.js - 安装 nodeclipse 返回错误

macos - 无法在优胜美地机器上使用 pem key 连接到 ec2 实例

amazon-web-services - 使用 ec2-describe-tags 时如何获取仅运行实例的列表