无法使用Socket.io启动NodeJS Server

时间:2018-05-20 17:15:29

标签: node.js express server socket.io mern

所以,我有一个简单的梦想用Socket.io库启动服务器,但由于某些原因它不会发生...我无法理解什么是错的,因为我甚至没有得到服务器运行的标准消息 - Server running on port ${port}

请帮助......

'use strict'

const express = require('express');
const http = require('http');
const io = require('socket.io');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcrypt-nodejs');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

const app = express();
const server = http.Server(app);
const socketServer = io(server);
const router = express.Router();

const chat = require('./routes/chat');
const profile = require('./routes/profile');
const registration = require('./routes/registration');
const login = require('./routes/login');
const logout = require('./routes/logout');

const EmployersSchemaDB = require('./SchemaDB/EmployersSchemaDB');
const MessagesSchemaDB = require('./SchemaDB/MessagesSchemaDB');
const User = require('./SchemaDB/ShemaAuthtificaion');

mongoose.connect('mongodb://test_db');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
    res.setHeader('Cache-Control', 'no-cache');
    next();
});

app.use(session({
    secret: 'work hard',
    resave: true,
    saveUninitialized: false,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

router.route('/')
    .get((req, res) => {
    res.json('Hello on the Homepage!');
});

app.use('/', router);
app.use('/chat', chat);
app.use('/profile', profile);
app.use('/auth/login', login);
app.use('/auth/logout', logout);
app.use('/auth/registration', registration);

const port = process.env.API_PORT || 8989;
socketServer.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

2 个答案:

答案 0 :(得分:2)

从此改变:

socketServer.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

到此:

server.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

您需要启动您的http服务器。这是核心服务器,可与Express和socket.io一起使用,并记录所有传入的请求。

您的变量socketServer和您的io变量名称错误(这可能是您混淆的一部分)。 socketServer是实际的服务器,这是socket.io服务器端实例,通常名为io。有关详细信息,请参阅the socket.io server doc

答案 1 :(得分:2)

您应该从更简单的服务器开始:

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

app.use(express.static(`./public`));

socket.on('connect', socket => {
  socket.emit('identify', {'server':'server data'});
});

socket.on('data', data => {
  console.log(data);
});

server.listen(4000, () => {
  console.log('Server up and running on port 4000');
});

在前端你可以这样测试:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test</title>
  </head>
  <body>test
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
    <script type="text/javascript">
      'use strict';
      var socket = io('http://localhost:4000');

      socket.on('identify', function (socket) {
        console.log(socket);
      });
    </script> 
  </body>
</html>