javascript - 为什么会出现“加载资源失败”错误?
问题描述
我正在尝试使用 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 中的脚本标记内,它就可以工作。但不像我正在尝试这样做。
解决方案
尝试添加app.use("/scripts", express.static(__dirname + "/node_modules/socket.io"));
到您的代码中。
然后,从 /scripts/socket.io.js 加载脚本。希望这有助于或引导您朝着正确的方向前进。
推荐阅读
- angular - 错误错误:未捕获(承诺中):TypeError:无法读取未定义的属性“id”
- sql-server - 使用 SSDT 的 SQL Server 架构和数据比较
- javascript - 如何在 TypeScript React 组件中返回字符串或 JSX 元素?
- javascript - 为什么selly api 只显示我拥有的+400 中的20 个产品?
- python - 按日期和条件不匹配结果汇总 Python pandas 列
- r - R for 循环只通过一个向量
- python - 删除字母 S 后需要在输出中获取 4 个 URL 但只获取最后一个 URL
- css - CSS 样式:如何在 React 中重新创建 iOS 14 段控件?
- css - CSS动画,一些动画完成,然后按顺序重复
- python - 更新类外的类标签