nodeJS:在前端

时间:2017-12-15 19:18:36

标签: javascript node.js sockets heroku

当我在localhost上运行带有nodemon的nodejs app时,在前端,socket.io没有显示,如果我将/socket.io/socket.io.js放在url的末尾,则不会显示套接字库。我得到的错误如下: Chrome Debug Error msg

我在代码的服务器和客户端设置了socket.io并安装了软件包。

这是代码中socket.io的声明错误,还是socket.io的系统错误? [我正在使用localhost和Heroku]

编辑: 更改了index.html文件中的语法错误,并将app.listen更改为server.listen

New Chrome Error msg

server.js:

const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');

const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);

app.use(express.static(publicPath));

io.on('connection', (socket) => {
  console.log('New user connected');

  socket.on('disconnect', () => {
    console.log('User was disconnected');
  });
});

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

index.html的(客户端):

<!DOCTYPE html>

<html>

<head>
  <meta charset="utf-8">

</head>

<body>
  <p>Welcome to the chat app</p>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('connect', () => {
      console.log('Connected to server');
    });

    socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  </script>
</body>

的package.json:

{
  "name": "chat-app",
  "version": "1.0.0",
  "description": "",
  "main": "server/server.js",
  "scripts": {
    "start": "node server/server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "engines": {
    "node": "8.8.1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "socket.io": "^2.0.4"
  }
}

1 个答案:

答案 0 :(得分:1)

html文件中有拼写错误。替换此行:

<script> src="/socket.io/socket.io.js"></script>

使用

<script src="/socket.io/socket.io.js"></script>

那是&#34; SyntaxError:输入的意外结束&#34;从你的截图中揭示。