socket.io - ReferenceError: io is not defined - javascript

I am writing an application for Android 2.3.5 (that will also be compatible with iOS). I wish to transfer data from the app's HTML/Javascript to a Python program on a server (which uses the Twisted engine to retrieve the data).
I've tried many things and looked at various forums, answers, tutorials, and web pages--including most of them here--and can't find an answer. Here's the relevant Javascript I have in my index.html file:
<script src="socket-lib/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
function sendData() {
try {
var socket = io.connect('http://mywebsite.com:12345');
socket.on('connect', function(data) {
socket.send('Hello.');
socket.on('message', function (msg) {
socket.send('This is where I send data?');
});
});
}
catch(err) {
alert('ERROR: socket.io encountered a problem:\n\n' + err);
}
} // end of sendData
If you can't tell, I'm still pretty confused how this works; I can't even test anything. The error that keeps coming up is ReferenceError: io is not defined. Some sites used something like var io = require('socket.io');. But then it results in the same error: ReferenceError: require is not defined.
I put the socket-lib folder in assets/www, where any other Javascript source should go. This is also where the index.html file is. Many sites use <script src="/socket.io/socket.io.js"></script>, but this makes no sense to me. Many sites also imply the use of node.js, but I never see it anywhere.
How can I make this work?
Reply edits:
I tried it in Chrome, and it's giving me an Uncaught ReferenceError: require is not defined for the socket.io.js file. So I decide to source in require.js right before it. Then it gives the error Uncaught Error: Module name "socket.io-client" has not been loaded yet for context. Since I'm not using this, I care not. When I try the connection, though, it gives the same io is not defined error. When I define it as var io = require('socket.io'), the error is Error: Module name "socket.io" has not been loaded yet for context: _ http://requirejs.org/docs/errors.html#notloaded. I looked at the website, and it doesn't help me at all. When I try to put "require" as a function argument, another error occurs: TypeError: undefined is not a function.

I found the answer for anyone who gets immensely confused by the horrible lack of documentation of socket.io.
You cannot source /socket-lib/socket.io.js,
you must source http://yourwebsite.com:12345/socket.io/socket.io.js.
The server automatically does the rest for you.

I solved it myself by changing index.html to import the socket io client from bower, first i installed the bower component:
bower install socket.io-client
then i changed the reference in index.html to :
<script src="bower_components/socket.io-client/socket.io.js"></script>
Or file could be found at - lib/socket.io-client/dist/socket.io.js

I managed to blunder through this, and squandered about an hour, on something that turned out to be a very basic error.
When an function is not defined? Such as " Uncaught ReferenceError: io is not defined ". Does that not mean that the function is getting "used" before it is "created"?
In the part of my HTML file, that "calls" the javaScript files, it looked like this :
<script src='./js/playerChatter.js'></script> <!-- this one calls io -->
<script src="http://localhost:2019/socket.io/socket.io.js"></script><!-- This Creates io -->
and i changed it to this
<script src="http://localhost:2019/socket.io/socket.io.js"></script> <!-- This Creates io -->
<script src='./js/playerChatter.js'></script> <!-- this on calls io -->
So now the item "io", whether it is an object or function... Is actually getting created before it is getting used :D
Have FUN!

write server side code in socket.io.js file and try src="/socket.io/socket.io.js"
hope this will solve your problem

When getting socket.io to work with many other libraries using require.js I had same error, it turned out to be caused because of trying to load the socket.io.js file from the same /js folder than the rest of the other files.
Placing it in a separated folder, fixed it for me, you can see the code in this gist but all I changed for making it work, was this:
instead of:
socketio: 'socket.io',
Use:
socketio: '../socket.io/socket.io',
Not sure about the reason of this behavior, but I hope it helps you.

This looks like your browser cannot find the socket.io.js file. You could try opening the index.html on your computer with Firefox+Firebug or the Chrome Web Developer Tools and look at how the .js file is requested. On the other side, you could check the logs on the webserver serving the .js file whether there are any file not found errors.
The require function would be provided by e.g. RequireJS, but you would still need to configure the paths to your scripts correctly for it to work.

For me after debugging through all of the very helpful suggestions, it turned out to be simply that my node server had stopped. I had been running it manually in a terminal window during dev.
Make sure your node [yourservercode].js is running on the specified port! :-]

I use jspm.
Add this:
import 'btford/angular-socket-io/mock/socket-io';

In my case, using Unity WebGL with C# UnitySocketIO plugin, I need to add delay (1 sec) between Init and Connect, because the first method did not have time to add a new JS Socket object and code (listeners) to the page to work with it..

As mentioned in other answers, you have to use the complete URL.
<script src="http://127.0.0.1:5565/socket.io/socket.io.js "></script>
if it's giving you an error 404 please check whether io is properly instantiated on your server.js.If not please refer following to instantiate the io properly.
<script>
var socket = io();
</script>
In your server.js
const app = express();
const http = require('http'); //from express module
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

got to url /socket.io/socket.io.js and check if a js file is served or not if yes then instead of writing
var socket = io();
write
window.onload= function(){
var socket = io();
}

Related

How to connect to a Sqlite db from an HTML file via Javascript

I would like to insert data into a SQlite3 db by pressing a button from an HTML file.
In order to achieve this, I wrote a JS script.
Unfortunately, when I press the button, I get this error message in my console.log:
script.js:5 Uncaught ReferenceError: require is not defined
Then, I tried to convert my JS file with browserify but then I got this error:
Cannot read property '_handle' of undefined
Here my HTML and JS codes to reproduce the error:
HTML:
<head>
</head>
<body>
<div>
<label>SQLite3</label>
<button type="button">Connection</button>
</div>
<script src="script.js"></script>
</body>
JS:
function addData() {
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./data.db');
db.run('INSERT INTO info (result) VALUES (10)', function(err, row) {
if(err) {
console.log(err.message);
}
console.log("entry added to table");
});
}
addData();
Browserify works around the problem that browsers don't have native support for the Node.js module system.
Browserify does not work around most other APIs that are provided but Node.js but not browsers. For example, Node.js has the fs module which allows you to access the file system of the computer the code is running on. Browsers, on the other hand, don't allow access except in very particular and limited ways.
Since new sqlite3.Database('./data.db') tries to read data from a file, it will not work in a browser.
Use a different API that is supported by browsers instead (such as IndexedDB or Web Storage.
Alternatively, if you want to share data between browsers, use Node.js to run a web server (e.g. with Express.js) and write a web service through which the database can be accessed.
You can't connect to sqlite databawe from client side you have to connect from server side language. Perhaps you can use NodeJS as server side programming language.
follow those steps then it will work
STEP1
Download and install node js from https://nodejs.org/en/download/
STEP2
Install npm by folloy this instruction
https://www.npmjs.com/get-npm
STEP3
Create Node js project by following this guides http://cassandrawilcox.me/setting-up-a-node-js-project-with-npm/
STEP4
Now you can install sqlite3 via npm.
After that you have to run server. If you are beginner then follow this
https://www.w3schools.com/nodejs/

Execute NPM module through cordova

I created an app using cordova and everything is fine, expect I need to use a node module which doesn't have a client-side equivalent because I'm dealing with file write streams etc. I have found Cordova hooks to be my best shot so far, where I create an app_run hook to execute a node file that runs a socket server to listen for events from the client side.
I know, a very longwinded solution, but seems logically correct to me, the issue is that when I do create the server, building the app through Visual Studio 2017, the app launches on my android phone, but VS hangs on the "deploy" stage. I guess that it has to do with the event chain, so I created an asynchronous script like this:
(async function () {
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (socket) {
console.log('heyo')
socket.emit('hello world', 'hi')
})
server.listen(3000, function (err) {
if (err) throw err
console.log('listening on port 3000')
})
})();
but this doesn't seem to work either, somehow VS hangs on "deploy". If anyone can possibly guide me in the right direction, that would be highly appreciated.
PS: I know the title is off, but every time I use StackOverflow to get help with a particular attempt, I'm told to do it another way, so I'll leave it open.
If the goal is to use socket.io in your cordova app, there IS a JS client for the web that you need to use and you don't need to use npm for that, just add a link to your client js file in your index file. (should be in a "client" folder when you init socket.io via npm).
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost');
</script>
https://socket.io/docs/client-api/

io is not defined -- HTML/Javascript-Meteor app

I am trying to develop a chat component having my server side code in Meteor. To establish a socket connection I want to expose io object which we get from npm library socket.io-client.
I am adding a script tag to my HTML page which looks as shown below
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Then I am trying to connect to server side socket as shown below
var socket = io('http://localhost:3000');
This is where I get "io is not defined" error
Any leads would be appreciated.
Try using this
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
instead of
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
am adding a script tag to my HTML page which looks as shown below
Use the wrapper package instead:
https://atmospherejs.com/joncursi/socket-io-client
io would be defined but its CORS issue
Follow the instructions in https://enable-cors.org/server_meteor.html

Meteor package working on browser but not on server

There's no problem using the Meteor package strikeout:string.js on the client side (browser JS console), but it throws an error when using it on the server side.
Checked package.js and found api.addFiles('lib/string.js', ['client','server']);, is this not sufficient?
Test code
console.log(S('jon').capitalize().s)
Error on server
ReferenceError: S is not defined
is this not sufficient? YES, you are getting the Reference because you are not requiring it.
In order to use it on the server, you should require it, on this example im using meteorhacks:npm.
It was not possible for me create a Meteorpad of this, so i will do here step-by-step.
First meteor add meteor hacks:npm
Second On the recent create packages.json add this line
{
"string": "3.1.0"
}
Third Now just add the server code.
if (Meteor.isServer) {
Meteor.startup(function () {
var S = Meteor.npmRequire('string'); //server side
console.log(S('jon').capitalize().s)
});
}
Expected Output
I20150326-10:54:05.639(-5)? Jon
Hope it works for you.

socket.io.js not loading

I know there are a bunch of questions on this already, but none have answered it for me, and plus mine is slightly different.
I'm starting the socket.io server in node using this:
var io = require('socket.io').listen(8000);
My terminal says everything is ok:
info - socket.io started
Now I am trying to load the .js file in my clientside browser using this url:
http://<hostname>:8000/socket.io/socket.io.js
I dont get a 404, it just hangs forever. I've also used a network utility to ping port 8000, and it seems to be open fine.
I installed node and socket.io just yesterday, so they should be the latest versions. Can anyone shed any light on this? Thanks!
Turns out the reason I could never request the .js file was because my company network blocks all ports except the usual ones (80, 21, etc), so `I would never be able to communicate with port 8000.
Use express.js. Place the socket.io file in public/javascripts folder and add this line to your html
<script src="/javascripts/socket.io.js"></script>
I think this is the best way. When you're writing http://<hostname>:8000/socket.io/socket.io.js
node tries to find a folder named socket.io in your project's public folder. And the file socket.io.js in it.
If you don't want to use express.js you should catch the request and try to load a file if no routes were found for your request (what actually express does) because node doesn't know what to do for requests which don't match any routes in your server.
And I recommend to use the socket.io.min.js file (it's smaller and it's in folder node_modules\socket.io\node_modules\socket.io-client\dist)
You have to start an http/https server to access it via http/https. Simply starting an socket.io server won't do. Do the following:
var http = require('http');
var app = http.createServer(),
io = require('socket.io').listen(app);
app.listen(7000, "0.0.0.0");
Then I can access the file http://localhost:7000/socket.io/socket.io.js
sockets.io uses websocket protocol (ws://). See the wikipedia page.
You need to get at least 3 pieces working together.
Serve some HTML (/index.html will do just fine) so there's a web page. This file should contain the socket.io client <script> tag. For this you need the http server portion of the starter examples. You are missing this and that's why browsing to your server just hangs.
Serve the socket.io client. Socket.io will do this for you automatically when you pass in your http server function to it. You don't need full express as this can be done with just node's http module as per the first example on the socket.io docs.
Some javascript to actually do something with the socket. This can be the content of a <script> tag in index.html or a separate file. If it's a separate file, you need to set up your http server to actually serve it.

Categories