我没有在我的节点应用中连接Socket IO
,我认为它与我的EJS配置以及我如何呈现index.ejs
和layout.ejs
文件有关:
当我连接到Socket IO
时,我想控制用户已连接的日志:
io.sockets.on('connection', (socket) => {
console.log('user is connected')
socket.on('send-message', (data) => {
io.sockets.emit('new-message', data)
})
以下是我在localhost:3000
处理后端的方法,这是我的代码:
app.get('/', (req, res) => {
res.render('index')
})
但是当我转到localhost:3000
时,它无法控制用户已连接到Socket IO
我也尝试了这个:
app.get('/', (req, res) => {
res.sendFile('index.ejs', {root:__dirname})
})
以及
app.get('/', (req, res) => {
res.sendFile(process.env.PWD+'/client/views/index.ejs')
})
但我仍然没有连接。
任何想法我需要做什么?
更多代码:
服务器/ app.js
const
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
ejs = require('ejs'),
ejsLayouts = require('express-ejs-layouts'),
mongoose = require('mongoose'),
...
...
// environment port
const
port = process.env.PORT || 3000,
mongoConnectionString = process.env.MONGODB_URL || 'mongodb://localhost/context-app'
mongoose.connect(mongoConnectionString, (err) => {
console.log(err || "Connected to MongoDB (context-app)")
})
// ejs configuration
app.set('view engine', 'ejs')
app.set('views', process.env.PWD+'/client/views');
app.use(ejsLayouts)
app.get('/', (req, res) => {
res.render('index')
})
io.sockets.on('connection', (socket) => {
console.log('user is connected');
socket.on('send-message', (data) => {
io.sockets.emit('new-message', data)
})
})
server.listen(port, (err) => {
console.log(err || 'listening on my very special port ' + port)
})
客户端/视图/ layout.ejs
<!-- /views/layout.ejs -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Intro</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script>...</script>
<script>...</script>
<script>
var socket = io();
</script>
</head>
<body>
<% include partials/nav %>
<div class="container">
<%- body %>
</div>
</body>
</html>
客户端/视图/ index.ejs
<div id="main"></div>
<script type="text/babel" src="../app.js"></script>
编辑:解决方案
问题出在客户端:我只是忘了加载Socket IO
脚本:<script src="/socket.io/socket.io.js" charset="utf-8"></script>
答案 0 :(得分:1)
确保您在客户端加载socket.io脚本:
<script src="/socket.io/socket.io.js" charset="utf-8"></script>