gpt4 book ai didi

javascript - 无法使用 Node、Express 和 EJS 连接到 Socket IO

转载 作者:行者123 更新时间:2023-12-02 13:43:13 25 4
gpt4 key购买 nike

我没有连接到Socket IO在我的 Node 应用程序中,我相信它与我的 EJS 配置以及我的渲染方式有关 index.ejslayout.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)
})

client/views/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>

client/views/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>

最佳答案

确保您正在客户端加载 socket.io 脚本:

<script src="/socket.io/socket.io.js" charset="utf-8"></script>

关于javascript - 无法使用 Node、Express 和 EJS 连接到 Socket IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43130832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com