我是高级节点和表达教程的新手,并加入了一些有关免费代码营地的教程,其中一个教程可以在线和离线显示用户。我试图统计每次登录时加入聊天的用户数量在我使用过socket.io实时Web应用程序,但似乎根本不起作用,这是我的server.js代码
'use strict';
const express = require('express');
const session = require('express-session');
const bodyParser = require('body-parser');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const auth = require('./app/auth.js');
const routes = require('./app/routes.js');
const mongo = require('mongodb').MongoClient;
const passport = require('passport');
const cookieParser= require('cookie-parser')
const app = express();
const http = require('http').Server(app);
const sessionStore= new session.MemoryStore();
const io = require("socket.io")(http);
const passportSocketIo = require("passport.socketio");
const cors = require("cors");
app.use(cors());
fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'pug')
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
key: 'express.sid',
store: sessionStore,
}));
mongo.connect(process.env.DATABASE, (err, db) => {
if(err) console.log('Database error: ' + err);
auth(app, db);
routes(app, db);
var currentUsers = 0;
http.listen(process.env.PORT || 3000);
io.use(passportSocketIo.authorize({
cookieParser: cookieParser,
key: "express.sid",
secret: process.env.SESSION_SECRET,
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
}));
function onAuthorizeSuccess(data, accept) {
console.log("Success connection to socket.io");
accept(null, true);
accept();
}
function onAuthorizeFail(data, message, error, accept) {
if(error)
throw new Error(message);
console.log("failed connection to web socket", message);
accept(null, true);
if(error)
accept(new Error(message));
}
//start socket.io code
io.on("connection", function(socket) {
console.log('user ' + socket.request.user.name +' connected');
++currentUsers;
socket.on("disconnect", (socket) => {
--currentUsers;
});
//io.emit('user count', currentUsers);
socket.on('user', function(data) {
$('#num-users').text(data.currentUsers+ " users online");
var message = data.name;
if(data.connected) {
message += " has joined the chat.";
} else {
message += " has left the chat.";
}
$('#messages').append($('<li>').html('<b>' + message + '<\/b>'));
});
io.emit('user', {name: socket.request.user.name, currentUsers, connected: true});
});
//end socket.io code
});
这是chat.pug的代码
html
head
title FCC Advanced Node and Express
meta(name='description', content='Home page')
link#favicon(rel='icon', href='https://hyperdev.com/favicon-app.ico', type='image/x-icon')
meta(charset='utf-8')
meta(http-equiv='X-UA-Compatible', content='IE=edge')
meta(name='viewport', content='width=device-width, initial-scale=1')
link(rel='stylesheet', href='/public/style.css')
body
h1.border.center FCC Advanced Node and Express
h2.center Socket.IO Chat Room
.chat.center
p#{num-users}
.chat-box
ul#messages
form(action='')
input#m(autocomplete='off')
button Send
a#logout(href='/logout') Logout
script(src='https://code.jquery.com/jquery-2.2.1.min.js', integrity='sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00=', crossorigin='anonymous')
script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.2/socket.io.min.js')
script(src='/public/client.js')
这是client.js的代码
$( document ).ready(function() {
/*global io*/
var socket = io();
socket.on("user count", function(data) {
console.log(data);
});
// Form submittion with new message in field with id 'm'
$('form').submit(function(){
var messageToSend = $('#m').val();
//send message to server here?
$('#m').val('');
return false; // prevent form submit from refreshing page
});
});
它总是向我显示此错误消息: “您应该在“用户”甚至侦听器中的客户端上更改#num-users的文本,以显示当前连接的用户” 基本上,它要求在那使用JQuery更改“ num-users”的ID以显示在线用户的数量,但是它不起作用 我可以看到原因吗?