首页 > 解决方案 > 为什么会出现“加载资源失败”错误?

问题描述

我正在尝试使用 socket.io 和 node.js 创建一个聊天应用程序。

我正在关注 socket.io 网站上的教程,但我无法让控制台日志显示。

这是我的代码:

index.js

const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', socket => {
  console.log('a user connected');
});

http.listen(3000, () => console.log('Listening to 3000'));

索引.html

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        font: 13px Helvetica, Arial;
      }
      form {
        background: #000;
        padding: 3px;
        position: fixed;
        bottom: 0;
        width: 100%;
      }
      form input {
        border: 0;
        padding: 10px;
        width: 90%;
        margin-right: 0.5%;
      }
      form button {
        width: 9%;
        background: rgb(130, 224, 255);
        border: none;
        padding: 10px;
      }
      #messages {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }
      #messages li {
        padding: 5px 10px;
      }
      #messages li:nth-child(odd) {
        background: #eee;
      }
    </style>
    <script src="/socket.io/socket.io.js"></script>
    <script src="client.js"></script>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

客户端.js

const socket = io('http://localhost:3000');

如果我将此行( const socket = io(); )放在 .html 中的脚本标记内,它就可以工作。但不像我正在尝试这样做。

标签: javascriptsocket.io

解决方案


尝试添加app.use("/scripts", express.static(__dirname + "/node_modules/socket.io"));到您的代码中。

然后,从 /scripts/socket.io.js 加载脚本。希望这有助于或引导您朝着正确的方向前进。


推荐阅读