简体   繁体   中英

socket.io-client object is not a function

I opened a question here earlier ( Socket.io trigger events between two node.js apps? ), this was much help, but I am confused out of my mind.

I keep getting object is not a function on my client side script.

A little setup, I have a front end site that is served with express localhost:9200 then I have a back end app localhost:3100 that is also served with express and I am trying to emit events from localhost:9200 to the socket.io server localhost:3100

Client script for website localhost:9200

// I have tried many different ways
var socket = io('http://localhost:3100');
var socket = io('http://localhost');
var socket = io();

EDIT

The issue was with the above of course, because io in the above case for some reason was an object when it should be a function, I came across an old post which mentioned using var socket = io.connect('http://localhost:3100'); connect and that worked, I though it was depreciated or something, I have no clue why the docs don't mention this but it fixed my issue.

All result in object is not a function. I include the client side script like this

// tried some different ways
<script src="http://localhost:3100/socket.io/socket.io.js"></script>
<script src="socket.io/socket.io.js"></script> // this is a 404

I have installed https://github.com/automattic/socket.io-client and on the server for the front end website :9200 I have set it up like.

// tried a couple ways to connect
var socket = require('socket.io-client')('http://localhost:3100');
var socket = require('socket.io-client')('http://localhost');
  socket.on('connect', function(){});
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});

I am confused on how to properly configure this so that I can get my site to emit socket events to my server and visa versa?

Well I figured it out, this is pretty ridiculous but on the client side javascript I needed to add var socket = io.connect('http://localhost:3100'); the io.connect made it work versus var socket = io('http://localhost:3100');

Maybe I missed it but the docs don't say to use io.connect https://github.com/automattic/socket.io-client whatever it works and I am happy, any thoughts on why the docs don't mention this would be great.

The difference is io.connect is pre 1.0 syntax. They changed it for whatever reason. These are the exact kind of fun surprises I have come to expect in socket.io.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM