快速js聊天应用程序:socket.io.js文件出现404错误

Express js chat application:404 error on socket.io.js file

本文关键字:js 错误 文件 socket 聊天 应用程序 快速 io      更新时间:2023-09-26

我正在尝试使用Express js(翡翠模板)和socket.io开发聊天应用程序。这里是我的app.js

var express = require('express');
var path = require('path');
var http = require('http');
var io = require('socket.io')(http);
var app = express();
//start chat with socket io
io.sockets.on('connection',function(socket){
  console.log("connection");
  socket.on('send message',function(data,callback){
    var msg=data.trim();
    if(msg==null){
      callback("enter a messsage");
    }else{
      console.log("chat message"+msg);
      io.sockets.emit('new message',{msg:msg});
    }
  });
});
//end socket

这是我的chat.js文件在客户端

$(document).ready(function(){
    var socket=io.connect('http://localhost:3000');
    var $message=$('#message');
    var $messageForm=$('#send-message');
    //opens a connection and send to sever
    $messageForm.submit(function(e){
             e.preventDefault();
             socket.emit('send message',$message.val(),function(data){
              console.log("data"+data);
             });
             $message.val('');
           });
    //read the chat messages from users
    socket.on('new message',function(data){
        console.log('data.msg');
    });
});

chat.jade file

<form id="send-message">
<input type="text" id="message">
<input type="submit" value="submit"/>
</form>
<script src="http://localhost/api/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>

我将得到404错误在这个文件http://localhost:3000/socket.io/socket.io.js。还可以在chat.js脚本中获得Uncaught ReferenceError: io is not defined。我想这是因为缺少socket.io.js文件。

你有几个问题。
在jade模板中提供静态文件,您应该使用如下内容:

link(rel='text/javascript', href='/js/socket.io.js')    

这些文件通常包含在express应用程序的public目录中。然后在你的app.js中,你应该有这样的内容:

app.use(express.static('public'));  

在express网站上有解释- http://expressjs.com/starter/static-files.html

其他地方的

Uncaught ReferenceError: io is not defined  
$(document).ready(function(){
    var socket=io.connect('http://localhost:3000');

这是因为您没有在客户端上定义io。在io上调用connect,但没有在任何地方声明/定义io

您还没有在应用端创建套接字服务器。你应该这样做:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
  console.log('Server listening at port %d', port);
});  
io.on('connection', function (socket) {
    // when the client emits 'new message', this listens and executes
    socket.on('new message', function (data) {
        // we tell the client to execute 'new message'
        socket.broadcast.emit('new message', {
        });
    });


套接字。我在github上有一个聊天应用的例子,你可以作为参考。你的chat.js将相当于他们的公共/main.js
你的chat.jade相当于他们的公共/index.html
你的app.js匹配他们的index.js