我创建了一个数据库连接,并从服务器端的db中获取数据。如何将我的数据从服务器端传递到node.js中的客户端javascript。请帮帮我,我读了很多谷歌搜索,但没有找到任何有用的东西。 我正在使用Emitter参加我的活动。现在它正在使用serveride,我无法将数据传递给客户端。
这是我的代码:
var dbrows;
// Connecting to Database.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ''
});
var DBName = 'use ChatDB';
connection.connect();
connection.query(DBName);
connection.query('SELECT * from chat', function(err, rows, fields) {
if (err) throw err;
dbrows = rows;
});
connection.end();
// Event Emitter emits out pre-defined events.
var EventEmitter = require("events").EventEmitter;
var Emitter = new EventEmitter();
Emitter.on('ChatUsers', function () {
console.log(dbrows);
});
答案 0 :(得分:0)
如果您不必使用Emitter
,建议您使用socket.io
等WebSocket库。它使用简单。对于您的代码,您可以编写如下内容:
io.on('connection', function (socket) {
socket.on('sendUsers', function (data) {
connection.connect();
connection.query(DBName);
connection.query('SELECT * from chat', function(err, rows, fields) {
if (err) throw err;
socket.emit('sendUsers', rows);
});
connection.end();
});
});
在客户端:
socket.on('sendUsers', function(data){
console.log(data); // here you have your db records.
});
此处有更多信息和示例:
答案 1 :(得分:0)
这是服务器端代码:
// This file is required by app.js. It sets up event listeners
// for the two main URL endpoints of the application - /create and /chat/:id
// and listens for socket.io messages.
// Use the gravatar module, to turn email addresses into avatar images:
var gravatar = require('gravatar');
// Export a function, so that we can pass
// the app and io instances from the app.js file:
module.exports = function(app,io){
app.get('/', function(req, res){
// Render views/home.html
res.render('home');
});
app.get('/create', function(req,res){
// Generate unique id for the room
var id = Math.round((Math.random() * 1000000));
// Redirect to the random room
res.redirect('/chat/'+id);
});
app.get('/chat/:id', function(req,res){
// Render the chat.html view
res.render('chat');
Emitter.emit('ChatUsers');
});
// Initialize a new socket.io application, named 'chat'
var chat = io.of('/socket').on('connection', function (socket) {
// When the client emits the 'load' event, reply with the
// number of people in this chat room
socket.on('load',function(data){
if(chat.clients(data).length === 0 ) {
socket.emit('peopleinchat', {number: 0});
Emitter.emit("ChatUsers");
}
else {
socket.emit('peopleinchat', {
number: 1,
user: chat.clients(data)[0].username,
avatar: chat.clients(data)[0].avatar,
id: data
});
}
});
// THIS IS YOUR CODE WHAT YOU WROTE FOR ME:
socket.on('sendUsers', function (data) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
});
var DBName = 'use ChatDB';
connection.connect();
connection.query(DBName);
connection.query('SELECT * from chat', function(err, rows, fields) {
if (err) throw err;
socket.emit('sendUsers', rows);
});
connection.end();
});
// When the client emits 'login', save his name and avatar,
// and add them to the room
socket.on('login', function(data) {
console.log(data);
// Use the socket object to store data. Each client gets
// their own unique socket object
socket.username = data.user;
socket.room = data.id;
socket.avatar = gravatar.url(data.avatar, {s: '140', r: 'x', d: 'mm'});
// Tell the person what he should use for an avatar
socket.emit('img', socket.avatar);
// Add the client to the room
socket.join(data.id);
if(chat.clients(data.id).length >= 2 ) {
console.log(data.id);
var usernames = [],
avatars = [];
usernames.push(chat.clients(data.id)[0].username);
usernames.push(chat.clients(data.id)[1].username);
avatars.push(chat.clients(data.id)[0].avatar);
avatars.push(chat.clients(data.id)[1].avatar);
// Send the startChat event to all the people in the
// room, along with a list of people that are in it.
chat.in(data.id).emit('startChat', {
boolean: true,
id: data.id,
users: usernames,
avatars: avatars
});
}
});
// Somebody left the chat
socket.on('disconnect', function() {
// Notify the other person in the chat room
// that his partner has left
socket.broadcast.to(this.room).emit('leave', {
boolean: true,
room: this.room,
user: this.username,
avatar: this.avatar
});
// leave the room
socket.leave(socket.room);
});
// Handle the sending of messages
socket.on('msg', function(data){
// When the server receives a message, it sends it to the other person in the room.
socket.broadcast.to(socket.room).emit('receive', {msg: data.msg, user: data.user, img: data.img});
});
});
};