node.js: socket.io vs express.static - javascript

I have the following server.js running:
module.exports = server;
var express = require('express');
var fs = require('fs');
var server = express.createServer();
var port = 58000;
server.listen(port);
var io = require('socket.io').listen(server);
server.use(express.static('/', __dirname + '/../public'));
server.use(express.logger());
io.on('connection', function(client){
console.log('new client connected ' + client);
client.on('message', function(){
console.log('client wants something');
});
});
Simple express.static server for files in a /public subfolder, plus socket.io functionality. With this setup, any request for the 'socket.io.js' file fails, i.e.
http://localhost:58000/socket.io/socket.io.js
returns a 404 error (file not found). Static file server works correctly. If I simply use the 'http' module instead of 'express' (commenting out express.static and express.logger lines) socket.io.js is served correctly. How can I combine both functionalities?

Express 3.0.0 (lastest) change its API.
Here is a question very similar to yours that delivers the response.
var express = require('express')
, http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
...
server.listen(8000);

Make sure you have the last versions of express.js and of socket.io.js.
My side it's working great with
express#2.5.8
socket.io#0.8.5
node#0.6.5
Otherwise, a solution can be to call var io = require('socket.io').listen(server); after your server.use

Related

Using Express and Node to connect HTML, CSS, and Javascript to a server

I have HTML, CSS, and Javascript programs that work perfectly together. I've recently realized that I'm going to need a server to be able to complete some of my functionality. I've created a local Node server using some tutorials. After reading some suggestions, I'm trying to use Express to try to add the HTML, CSS, and Javascript to the Node, which are all in the same folder. The code I have (below) just causes the browser to stay on loading.
const http = require('http');
const fs = require('fs').promises;
const host = 'localhost';
const port = 8000;
var express = require('express');
var path = require('path');
var app = express();
const requestListener = function (req, res) {
app.use(express.static(path.join(__dirname, 'public')));
//res.writeHead(200);
//res.end("My first server!");
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
you don't need http module if you are using express...
const express = require('express')
const app = express()
// '/' is the url you want to host your site
// 'public' is the folder in which you have the necessary frontend files
// and the main html should be named as 'index.html' inside 'public'
app.use('/', express.static('public'))
app.listen(5000, () => console.log('server on port 5000'))
Try this....
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'css'));
app.use('/html',(req,res,next)=>{
res.sendFile(path.join(__dirname,'HTML','text.html');});
app.listen(3000);

Socket.IO server only accessible locally

I have a Socket.IO server (Node.js, NPM) that works fine, but the problem now is that it only works in LAN.
I'm using Socket.IO 2.1.1.
My IP is my IPv4 address, and the port is 80. Here is my server.js code.
var express = require('express');
//var http = require('http');
var url = require('url');
var socket = require('socket.io');
var crypto = require('crypto');
var fs = require('fs');
//App setup
var app = express();
var server = app.listen(80, function() {
console.log('listening to request on port 80! Yay!');
});
//Static files
app.use(express.static('public'));
io.on('connection', function(socket) {
//stuff to do on connection
}
and for the client
var socket = io.connect('http://192.168.254.7:80', {transports:['websocket']});
and I also included
<script language="javascript" src="http://<ipv4>:80/socket.io/socket.io.js"></script>
where IPv4 is the IP address i'm using.
How do I make it public? (not only locally / LAN) I've tried changing
io.connect('http://192.168.254.7:80', {transports:['websocket']});
to
io.connect();
I've even changed the port from 3000 to 8080, and to 80.
I let my friends try to access the website, and it always shows
net::ERR_CONNECTION_TIMED_OUT. Does it even load to the other's device?
Again, how do I make this public? Thanks.

Error :Enoent :no such file or directory ,stat 'D:\awesome-testindex.html'

I have a folder named awesome test and it contains index.hml ,node modules and server.js .Here is the server.js file and i am getting this error .
//grab express
var express=require('express');
//create an express App
var app=express();
// create an express route for the home page
// http://localhost:8080/
app.get('/', function(req, res) {
res.sendFile(__dirname + 'index.html');
});
// start the server on port 8080
app.listen(8080);
// send a message
console.log('Server has started!');
Here's where the error is:
res.sendFile(__dirname + 'index.html');
It should be:
res.sendFile(__dirname + '/index.html');
The reason for this is because the index.html is being added upon the directory, which doesn't end with a / by default. You need to add it yourself as shown above.
Hope this helps!
Edit: I tried Node.js before. I think it would be best if you added a "public" folder, with the .js file being above everything. Here's an example:
This was my code for my first Node.js server, as a reference:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const express = require('express');
const app = new express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, () => console.log("Example app listening on port 3000!"))
console.log("http://"+hostname+":"+port)
Note: To use express as shown above, you'll have to open a command line, and type in the following (assuming you have node.js installed correctly):
npm install -g express
Also, to make sure you installed both node.js, do the following:
Node: node -v
Hope everything helps! ^_^

Express Server returns Cannot Get when trying to access index.html

I referred to the previously asked question on this but couldnt resolve it. I have Express server installed and trying to run Index.html file through it.
But I am getting 'Cannot GET /' as the response.
Here is the server.js through which I calling the index.html
var express = require('express');
var app = express();
app.get('index.html', function (req, res) {
app.use("/", express.static(__dirname));
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Thanks in advance!!
When you access a directory on your hosted site, say the root directory of localhost on port 8080, using http://localhost:8080/ for URL, the browser does not send a request for 'index.html` to the server and just uses whatever the server sends back.
It's the express static middleware which in response to a browser request with no filename will check if the folder exists and (by default) return any index.html contained in the folder. So your line of code for routing, app.get('index.html') never executes, and the browser gives you the error message.
Here's a mini static express server if you want to try it.
var express = require('express');
var app = express();
app.use(express.static('../public')); // path to your public directory
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
If you want a simple static, folder-as-server kind of thing, you can do it without express way like "/public":
var fs = require("fs");
var host = "localhost";
var port = 8000;
var express = require("express");
var app = express();
app.use('/', express.static(__dirname));
app.listen(port, host);
I put this in the file express.js, so that is in the same folder than index.html (even associated .js with node.exe). This way the folder is the root of the server.

Using Socket.io With Express 4 on Different Pages and Understand Socket.io example code

First of all I know a similar question has been asked here, however, I did not understand the answer and my question is worded slightly differently so I am wondering if I can get a more clear answer.
The Express Generator starts an app like so:
app.js
var express = require('express');
var routes = require('./routes/index');
var users = require('./routes/users');
var io = require('socket.io');
(etc.)
I want to use Socket.io so I also install it and require it and following the Socket Docs do this
var server = express.createServer();
var io = require('socket.io')(server);
However, all of my routes, where I really want to handle socket.io events, take place on my routes/index.js page. How do I use socket.io with my router, which is on a different page? How do I pass it in when my server instance was started on app.js (a different page)?
Furthermore, the socket.io docs list two ways to get started with express. The first example shows:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And the second one shows:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Can anyone explain the difference between using the "Express Framework" and "With Express 3 /4" as the documentation differentiates. I would also love to know why the examples use express.createServer() (when a generated express app does not) and why the other example uses both the express and http node modules. Thank you
A working piece of code would be as given below. The important thing here is do all the work with io initialization and io handling once you start listenting on express server. Hope this helps. :-)
var app = require('express')();
var socket_io = require('socket.io');
app.io = socket_io();
// setup app routes and express settings starts ...
// ....
// ... setup app routes and express settings ends
var server = app.listen(app.get('port') || 3000);
app.io.attach(server);

Categories