gpt4 book ai didi

javascript - 引用 socket.io 时的错误

转载 作者:行者123 更新时间:2023-11-30 19:01:46 25 4
gpt4 key购买 nike

我正在尝试构建一个具有聊天功能的快速应用程序,但 socket.io 无法正常工作,它提供了未捕获的引用 please see an image of error here 运行服务器时出错。

在 www 文件中

var server = http.createServer(app);
require('../socket-server')(server);

在 socket-server.js 文件中

'use strict'

var socketIO = require('socket.io');

module.exports = function(server) {
console.log("success");
var io = socketIO(server);
io.on('connection', (socket) => {
socket.on('chatMessage', (data) => {
io.emit('chatMessage', data);
});
});
}

在task.hbs文件中

<div>
<div class="row">
<div class="col-md-8">
<textarea id="code-screen"></textarea>
</div>
<div class="col-md-4" id="chatbox">
<div class="panel panel-primary">
<div class="panel-heading">
CHAT ROOM
<span class="pull-right" id="chatbox-username">
{{#if user}}
{{user.name}}
{{/if}}
</span>
</div>
<div class="panel-body">
<ul class="media-list" style="height: 300px; overflow-y: scroll" id="chatbox-listMessages">

</ul>
</div>
<div class="panel-footer">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter The Message" id="userMessage">
<span class="input-group-btn">
<button type="button" id="chatButton" class="btn btn-primary">SEND</button>
</span>
</div>
</div>
</div>
</div>
</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>

{{!-- <script src="../node_modules/socket.io/lib/socket.js"></script> --}}
<script src="/socket.io/socket.io.js"></script>

<script>

var socket = io.connect('http://localhost:3000');
var editor = CodeMirror.fromTextArea(document.getElementById('code-screen'), {
lineNumbers: true,
theme: 'material'
});

var username = $("chatbox-username").val();
if(username === "") {
var userId = Math.floor(Math.random() * 9999).toString();
username = "User" + userId;
$(#chatbox-username).text(username);
}

var userMessage = function(name, text) {
return ('<li class = "media"> <div class = "media-body"> <div class = "media">' +
'<div class = "media-body"/>' +
'<b>' + name + '</b> : ' + text + '<hr/> </div> </div> </div> </li>'
);
};

document.getElementById('chatButton').addEventListener("click", sendMessage);

function sendMessage() {
var userMessage = $(#userMessage).val();
socket.emit('chatMessage', { message: userMessage, username: username });
$('#userMessage').val("");
};

socket.on('chatMessage', (data) => {
$('#chatbox-listMessages').append(userMessage(data.username, data.message));
});
</script>

我应该如何引用/socket.io/socket.io.js文件,以便可以引用脚本中的io变量。

最佳答案

替换

$(#chatbox-username).text(username);

$('#chatbox-username').text(username);

关于javascript - 引用 socket.io 时的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59445412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com