socket.io with Express 4.15 template from WebStorm

2019-09-20 08:01发布

I'm trying to setup a Node.js server with socket.io. I'm using the latest template given by WebStorm template.

My step is first add socket.io to my language and framework - Node.js and NPM. Here is my setting

enter image description here

Then in my "bin/www" I add the below

var io = require('socket.io')(server)

And add this to bottom of the bin/www file (after server has start listening)

io.on("connection",(socket)=>{
  console.log("user connected" + socket.id)
})

Then I modify my index.jade as below

extends layout

block content
  h1= title
  p Welcome to #{title}

  li what the ul1
  li what the ul2
  script.
    src="/socket.io/socket.io.js"
  script.
    var socket = io();

Run the server. visit the page and this is what I get

enter image description here

I get the error

Uncaught ReferenceError: io is not defined
    at localhost/:1

Anyone know what wrong with my implementation?

Edit 1: I can get to the socket.io.js by my browser enter image description here

1条回答
神经病院院长
2楼-- · 2019-09-20 08:25

I guess your browser can't find the library. You could include it by adding

src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"

to your file.

查看更多
登录 后发表回答