Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

javascript - Socket.io: io is not defined

So, I am trying to get data on my node.js file instead of directly getting it on my JS file.

I a using Socket.io 2 here, Below is a snapshot of my code and this is also the first time I am using Websocket with Node.

I am doing something like

var socket = require('socket.io')

//Home Page
app.get("/", function(req, res) {
var cryto = io.connect("https://xyfz.com/);
cryto.on('trades', function (tradeMsg) {
            console.log(tradeMsg);
          });
res.render("index");
});

I also tried something like

var io = socket("https://abc.io/"); 

and

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

which was throwing errors like server.listeners is not a function and io.connect is not a function.

I am certain that I messing up stuff here so can someone guide me about the correct way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two things which are wrong .

First Consider using Socket.io-client instead of Socket.io.

Second and very much important.

Never ever make API calls inside your routes. This will trigger a API call everytime user opens your website or webpage

You can also expect an error "Unexpected headers" or something like that.

Always, Try do declare it outside any routes in your NodeAPP.

Same goes for socket.io as well


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...