node.js app can't find socket.io - node.js

I installed socket.io in the app directory (along with express) and in the index.html file I link to it this way:
<script src="http://localhost:8080/node_modules/socket.io/lib/socket.io.js"></script>
I get a 404 on this request. I double-checked the link and it's fine. the node.js app runs on port 8080 and I have no idea why it doesn't work
UPDATE:
Apparently it is something to with Express. When not using it I don't have that problem and socket.io works fine.
This is he setup of my server file:
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.listen(8000);
and this is the front-end:
<script src="/socket.io/socket.io.js"></script>
<script src="js/vendor/jquery-1.8.3.min.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
Also, I switched the jQuery from google CDN to local and it doesn't find it too

Make sure you've made socket.io listening to external connections in your back-end. Basically socket.io has inside method of providing your socket.io.js file, so you should place your require ('socket.io').listen(app) before defining any routes to your app.
The correct url is :
<script src="/socket.io/socket.io.js"></script>
as randunel said.
So, your configuration should look like this :
UPDATED for express 3.x :
var express = require('express'),
http = require('http');
var app = express();
var server = http.createServer(app).listen(8000);
require('socket.io').listen(server); // Your app passed to socket.io
Server-side
<script src="http://localhost:8000/socket.io/socket.io.js"></script>

Don't use that whole path, it does not correspond to your project's directory structure. Just use
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
By the way, make sure that socket.io is also listening on 8080, not just the other services in your project.

Try putting your JS file in http://localhost:8080/javascripts/socket.io.js, basically the JavaScript directory of your public folder.

The way is the one from randunel.
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
If you link the file directly, you can get a "Welcome to socket.io" message instead of the file.
There's also a CDN socket.io.js file available to link, but it's outdated and will not work fine on new projects, so it's not recommended.

Related

Receive data from an HTML page, after receiving the information from the server by Nodejs

There is a site that has a page with a form that by submitting the form with the POST method, an HTML page is received and this received page has a LOADING and a few seconds later the LOADING is completed and the data is received. How can I do this in nodejs and get the data?
https://tracking.post.ir/?id=221670002100060770073113
To get you started, you'll need a few things: express, socket.io and some HTML code.
First, you'll need to install 2 essential node packages
npm install express socket.io --save
Secondly, you'll need to create a web server. Below is a very basic example:
const express = require('express'); // Define express
const app = express(); // Define the web app
const server = require('http').createServer(app); // Define the HTTP server
const io = require('socket.io')(server); // Define socket.io
app.get('/my/route', function(req, res) { // Listen for an incoming request
res.sendFile('/path/to/your/loading-page.html'); // Render your HTML loading file
// Load some data
io.emit('data-loaded', 'your-data'); // Emit your data to the client
});
server.listen(3000, () => console.log('Server is online'); // Allow your server to listen for incoming traffic
Now, you need to setup the receiving end (the client). In this example case this is the loading file
<!DOCTYPE html>
<html lang="en">
<body>
<!-- Some HTML code -->
</body>
<script src="/socket.io/socket.io.js"></script> <!-- Don't change this -->
<script>
let socket = io.connect(); // Connect to the server
socket.on('data-loaded', function() { // When the data has been loaded
// Do something with the HTML page
});
</script>
</html>
References:
- express docs
- socket.io docs
Hei, node.js is a JavaScript framework that works in the server-side of web applications. Like PHP.
You'd need to firstly create a node project setting up a node server.
getting started on node
to get POST parameters on node.js, you use request.body.name
where 'name'' stands for the name in the input field you have in the HTML form, just like the example below
<form action="yourAction">
<input type="text" name='yourName'>
<input type="submit" value='form'>
</form>
and in the node.js part, you type something like this
app.get('/yourAction', function(request, response){
console.log(request.body.yourName)
})

Socket.io connect from remote Cordova app - not allowed access

I am trying to access the Node.js socket.io server from my cordova app.
And then I receive the following error:
Failed to load https://www.ride4you.co.il/socket.io/?EIO=3&transport=polling&t=M30S1z4: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://127.0.0.1:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
This is the connection code in client side (the app or localhost):
<script src="https://www.ride4you.co.il/socket.io/socket.io.js">
</script>
<script type="text/javascript">
var socket = io("https://www.ride4you.co.il");
socket.on("disconnect", function() {
console.log("Disconnected");
socket = io();
console.log("Connected");
});
</script>
When I am trying this code from the actual domain, no errors and everything works. But from the app, which is not the origin domain, there is a block.
I have tried to remove this block, and allow every origin to access this socket with the next code in app.js (main node.js file):
var express = require('express');
var app = express();
var server = require('http').createServer(app);
global.io = require('socket.io').listen(server);
io.set('origins', '*:*');
But still got the same error there.
I know there is an option to allow for a specific domain, but I am using a cordova app which does not have a domain - so I think that is should be allowed by everyone, is not it?
Thanks.
use cors module on nodejs server and keep a copy of this file on your nodejs server https://www.ride4you.co.il/socket.io/socket.io.js and request it from your own server
Independent of node.js details (see Hemant Rajpoot's answer) It has to do with the fact that the request is authenticated (client side).
Please check this stackoverflow answer which is based on C#+angluar, but otherwise show the same behaviour/root cause:
CORS: credentials mode is 'include'

Provide an HTML page with JS with node.js and express

I am trying to serve an html page with a linked js script using node.js and express.
This is the server that provide the page:
var express = require("express");
var app2 = express();
app2.get('/', function(req, res) {
res.sendfile('./index.html');
});
app2.listen(process.env.VCAP_APP_PORT || 3000);
and this is the page:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Demo</h1>
<script src="/js/socket.io.js"></script>
<script src="/js/codice.js"></script>
</body>
As you can see I have two js scripts in my js folder but they are not loaded when I launch the page. What can I do?
What you would normally do is place any public resources (JavaScript files, CSS files, images etc) in a directory (Express names it public by default) and then use the express.static middleware in your app.configure call:
app.configure(function () {
// Various other middleware functions...
app.use(express.static(path.join(__dirname, "public")));
});
This effectively runs a static file server which will return any file inside the public directory. Currently, your browser is making a request for your JS files, but the Express server doesn't know what to do with them. They will eventually time out.
If you generate the initial state of your app with the global express executable (available if you installed Express via npm globally), it will set most of this up for you.

How do I serve the initial page in websockets

Ok so my question is concerning the websockets api...NOT socket.io. npm install websocket
Here's my problem.
I have written a little websockets server that can receive a message, interpret the textual message and send it back with a little extra text. Simple enough.
The message comes from an index.html file with a javascript...script written in it. Everything works as expected. The node server runs locally on my machine and when I want to test it out I just start the server then double click the index.html file which runs the script, which starts a new connection with node and done.
What I want is to be able to navigate my browser to "localhost" and the server start by giving the client the index.html file, which in turn will establish a connection with the server.
How can the user get the index.html file by simply navigating to a url (localhost in my case), if a connection is required to get the index.html file. In Socket.io it looks like this:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {});
If my question is still unclear here is a rewording: A user needs to be able to go to my url (localhost since node is running locally) and receive index.html. Like, all requests to the root receive an index.html file within a public directory.
The module you are using includes a complete example of how to use it with Express. It looks like it's written for the Express 2 API, so you have to tweak it if you're using Express 3:
var app = require('express')()
, http = require('http')
, server = http.createServer(app)
, WebSocketServer = require('websocket').server;
var wsServer = new WebSocketServer({
httpServer: server
});
server.listen(80);

Is socket.io.js supposed to return an empty file?

I trying to make a small chat website using node.js and socket.io.
To include the socket.io.js on my client-sided files:
<script src="192.168.0.108:1337/socket.io/socket.io.js"></script>
But is it normal that it returns an empty file?
http://screencast.com/t/HPAjAqV13q8q
I would also like to add that if on my server-sided file, I do res.write('Hello World'), the 'Hello World' Will appear on the web-page AND in the socket.io.js file
You can try this:
<script src='/socket.io/socket.io.js'></script>
And you should created a client io.connect
var socket = io.connect('http://localhost:5000');
You can also use socket.io's auto-discovery feature and don't specify the server
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
</script>
What solved it was opening the port on which socket.io was listening, in my case it was 8080... Now my socket.io.js has javascript code inside of it.
Now I am getting a 404 error on a xhr.send(null) in that socket.io.js file, but that is another story...

Resources