【发布时间】:2022-01-26 18:46:02
【问题描述】:
我正在使用 Express、Handlebars 和 Socket.IO 进行个人项目。我很好地设置了 Express 和 Handlebars 部分,但是当我尝试将客户端连接到 socket.io 时(通过将脚本标签放在页面上说的那样)它找不到它。我已经尝试安装“socket.io-client”,但它也没有工作,与出现在 socket.io 网站上的 CDN 安装相同。
这是我的服务器:
const express = require('express');
const app = express();
const port = 3000;
const exphbs = require('express-handlebars');
const engine = exphbs.engine;
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
const io = socketio(server);
app.engine('handlebars', engine());
app.set('view engine', 'handlebars');
app.set('views', './views');
app.use(express.static('public')); //Expongo al lado cliente la carpeta "public"
io.on('connection', socket => {
console.log(`Socket ${socket.id} connected`)
})
app.get('/', (req, res) => {
res.render("home");
})
app.get('/Hola', (req, res) => {
res.render("hola");
})
app.listen(port, ()=> console.log(`App listening to port ${port}`));
我把脚本标签放在主布局上:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Card Game</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<h1 id="titulo">Card Game</h1>
{{{body}}}
<script src="/socket.io/socket.io.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
程序在公共文件夹中找到 main.js 文件没有问题,但它似乎找不到 socket.io.js。
Screenshot of the console error that I get when I run the program
任何帮助将不胜感激!
【问题讨论】:
-
我怀疑您将不得不为这些依赖项添加另一个静态服务文件夹。 npm 安装项目依赖的 node_modules 文件夹。
-
@HiteshLala - 如果一切都正确安装,socket.io 的服务器端安装将自动为
/socket.io/socket.io.js自动提供服务,因此不需要其他静态服务。
标签: node.js express sockets socket.io handlebars.js