socket.io.js not found (404) - express

I am referring to an issue that has been asked many times but the solutions posted elsewhere are not resolving my problem ie socket.io.js not found.
The error message is
GET http://127.0.0.1:3000/socket.io/socket.io.js 404
Any help would be appreciated.
I referenced socket.io.js in my JADE file:
script(src='http://code.jquery.com/jquery.js')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js')
script(src='/socket.io/socket.io.js')
script(src='/javascripts/sockets/client.js') // this is in public folder
In my App.js file:
var express = require('express');
io = require('socket.io');
http = require('http');
app = express();
server = http.createServer(app);
io = io.listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
app.use(express.static(path.join(__dirname, 'public')));
These are the versions I am using:
"express": "~4.13.1",
"jade": "~1.11.0",
"morgan": "~1.6.1",
"serve-favicon": "~2.3.0",
"socket.io": "0.9.10"
Some additional info:
In my app.js: I referenced the server socket
// set up our socket server
require('./public/javascripts/sockets/server')(io);
'/javascripts/sockets/client.js' is my client socket:
var socket = io.connect('/');
socket.on('message', function (data) {
data = JSON.parse(data);
$('#messages').append('<div class="'+data.type+'">' + data.message +
'</div>');
});
$(function(){
$('#send').click(function(){
var data = {
message: $('#message').val(),
type:'userMessage'
};
socket.send(JSON.stringify(data));
$('#message').val('');
});

You shouldn't be using the socket.io package for this as it is primarily intended to construct a socket.io server instance. Instead you should be using socket.io-client which was specifically made to be used as the client socket.
I would recommend using bower to install this instead of npm as bower is made for front-end package management. Inside your project directory execute the following
note: If you don't have bower installed you'll need to install it globally npm i -g bower
bower init
bower install --save socket.io-client
Then you should make the bower_components directory created by installing the socket.io-client a static directory
server.use(express.static(path.join(__dirname, 'bower_components')));
Then change
script(src='/javascripts/sockets/client.js') // this is in public folder
to
script(src='/bower_components/socket.io-client)
Additionally, you're mixing your server and app variables. You should be using whatever variable your socket.io was created using, in this case you're using server so you should be using that. Your server file is mostly incorrect as you're instantiating many global values and you've created your io instance incorrectly.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.use(express.static(path.join(__dirname, 'public')));
server.use(express.static(path.join(__dirname, 'bower_components')));
server.listen(port, function(){
console.log('Express server listening on port ' + port);
});

Related

webRTC connection working when connecting to webpage hosted locally, but not when hosted on a server

I am attempting to create a webRTC connection from a python app to a web service using aiortc on python side, and express js on the web service side. When hosting the web service on localhost I have no problems, however when I host it on a server I am unable. I can still access the web page just fine when hosted online, I just get the following very generic exception when I attempt to make a webRTC connection:
socketio.exceptions.ConnectionError: Connection refused by the server.
Here is what I think is the relevant part of the python code:
import asyncio
import dataclasses
import os
import socketio
from pathlib import Path
from aiortc import RTCPeerConnection, RTCSessionDescription
from data_streams.StreamingTrack import StreamingTrack
# Socket.io details
NODEJS_URL = 'something.something.nl'
NODEJS_PORT = '4000'
ROOT = os.path.dirname(__file__)
CLASSROOM_ID = "defaultClassroom"
sio = socketio.AsyncClient()
await sio.connect("http://" + NODEJS_URL + ":" + NODEJS_PORT)
And here is what I believe is the relevant js code:
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
app.options('*', cors());
app.set('port', (process.env.PORT || 8080));
// initiating the socket server
const port = 4000;
const server = http.createServer(app);
const io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
io.sockets.on('error', (e) => console.log(e));
io.sockets.on('connect_error', (err) => {
console.log(`connect_error due to ${err.message}`);
});
If any additional code is needed I can provide it.
The firewalls have been disabled so I don't think that is the issue, I would greatly appreciate any suggestions as to why I am unable to connect.

How to set custom port number on swagger-api?

I created the project using the following command and chose Express framework.
swagger project create api-name
project starts on http://localhost:10010/
But I set my custom port number 10020.
Starting: /home/rajan/Documents/cse-4-1/web-lab/api/BankApi/app.js...
project started here: http://localhost:10010/
project will restart on changes.
to restart at any time, enter `rs`
try this:
curl http://127.0.0.1:10020/hello?name=Scott
My question is why second and last line showing different port number?
My app.js file:
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
//var port = process.env.PORT || 10010;
var port = 10020;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
I also set the port number on yaml file. Then fixed it.

Botkit With Express

The documentation at Botkit (https://github.com/howdyai/botkit/blob/master/readme-facebook.md) is pretty not meaningful at all:
// if you are already using Express, you can use your own server instance...
// see "Use BotKit with an Express web server"
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
Moreover, without a custom webserver (like express), Botkit doesnt provide a way to set the custom local url (instead, it simply chooses 0.0.0.0, which is impractical).
Is anyone successfully assembling app = require('express')(); into the setupWebserver in Botkit (specially for Messenger). If yes, please present the full code.
Hostname for the built in express server can be set when creating your controller:
var controller = Botkit.facebookbot({
hostname: 'YOUR_HOST_NAME',
verify_token: '',
access_token: ''
})
controller.setupWebserver and controller.createWebhookEndpoints are helper functions within botkit to do just what they describe, create an express webserver and webhook endpoints, respectively.
To implement your own webserver, you just need to setup a webhook endpoint for the botkit controller to receive message POST data at and perform auth handshakes.
By botkit convention this is /{platform}/receive so for facebook /facebook/receive but you can use whatever you like.
To use a custom express server with Botkit, first create a basic webserver.
// components/express_webserver.js
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var debug = require('debug')('botkit:webserver');
module.exports = function(controller, bot) {
var webserver = express();
webserver.use(bodyParser.json());
webserver.use(bodyParser.urlencoded({ extended: true }));
webserver.use(express.static('public'));
// You can pass in whatever hostname you want as the second argument
// of the express listen function, it defaults to 0.0.0.0 aka localhost
webserver.listen(process.env.PORT || 3000, null, function() {
console.log('Express webserver configured and listening at ',
process.env.HOSTNAME || 'http://localhost/' + ':' + process.env.PORT || 3000);
});
// Register our routes, in this case we're just using one route
// for all incoming requests from FB
// We are passing in the webserver we created, and the botkit
// controller into our routes file so we can extend both of them
require('./routes/incoming-webhook')(webserver, controller)
controller.webserver = webserver;
return webserver;
}
Next you need to create the routes for webhook endpoints, we're doing this in a separate file as is common with express
// components/routes/webhook.js
module.exports = function(webserver, controller) {
// Receive post data from fb, this will be the messages you receive
webserver.post('/facebook/receive', function(req, res) {
// respond to FB that the webhook has been received.
res.status(200);
res.send('ok');
var bot = controller.spawn({});
// Now, pass the webhook into be processed
controller.handleWebhookPayload(req, res, bot);
});
// Perform the FB webhook verification handshake with your verify token
webserver.get('/facebook/receive', function(req, res) {
if (req.query['hub.mode'] == 'subscribe') {
if (req.query['hub.verify_token'] == controller.config.verify_token) {
res.send(req.query['hub.challenge']);
} else {
res.send('OK');
}
}
});
}
Once you have created these two files, you will use require and pass your controller into the express module. Your main bot file should look something like this
// bot.js
var Botkit = require('botkit');
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot({
debug: true,
verify_token: process.env.verify_token,
access_token: process.env.page_token,
});
// Set up an Express-powered webserver to expose oauth and webhook endpoints
// We are passing the controller object into our express server module
// so we can extend it and process incoming message payloads
var webserver = require(__dirname + '/components/express_webserver.js')(controller);
You can find in github a, MIT-licensed, full Demo of running BotKit for Facebook Messenger on an Express server with MongoDB storage.
Here is the main server.js
// modules =================================================
var express = require('express') // framework d'appli
var app = express()
var bodyParser = require('body-parser') // BodyParser pour POST
var http = require('http').Server(app) // préparer le serveur web
var dotenv = require('dotenv')
var path = require('path')
// configuration ===========================================
// load environment variables,
// either from .env files (development),
// heroku environment in production, etc...
dotenv.load()
app.use(express.static(path.join(__dirname, '/public')))
// parsing
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing url encoded
// view engine ejs
app.set('view engine', 'ejs')
// routes
require('./app/routes/routes')(app)
// port for Heroku
app.set('port', (process.env.PORT || 5000))
// START ===================================================
http.listen(app.get('port'), function () {
console.log('listening on port ' + app.get('port'))
})
okay so here goes i was trying the same thing and have been able to start the botkit up with a custom url on express. You dont have to worry about this code at all:
controller.setupWebserver(process.env.port,function(err,webserver) {
controller.createWebhookEndpoints(controller.webserver, bot, function() {
console.log('This bot is online!!!');
});
});
This repository has its own code with will work with a mongodb database and a express server.
git clone https://github.com/mvaragnat/botkit-messenger-express-demo.git
sudo npm install express --save
sudo npm link body-parser
sudo npm link dotenv
sudo npm install --save botkit
sudo npm install --save monkii
sudo npm install --save mongodb
sudo npm install --save request
sudo npm install --save ejs
In all of the above steps you can perform:
sudo npm link botkit
etc
Finally run node server.js
lt --subdomain botkit --port 5000
restart node server.js
Dont Forget to add your variables to .env file in the directory.
All your traffic on local host will be redirected to the localtunnel, you can get a url using the lt --subdomain name --port 5000
Use this generated url in the webhooks on your page and your bot should be online.

Node express server, CORS API restriction, including an entry in my development machine’s hosts file

I am trying to use an API that has an API CORS policy that does not support browser requests from any domain. In order to allow clientside JavaScript code to access the API, whilst developing my application, I have been advised to I serve my webapp from '*.thisCompany.com' domain.
It was advised to include an entry in my development machine’s hosts file, as follows, which I have done:
$ echo '127.0.0.1 localhost.thisCompany.com' >> /etc/hosts
Following this command when I run sudo nano /private/etc/hosts
this is the screen that I see.
Host Database
localhost is used to configure the loopback interface
when the system is booting. Do not change this entry.
127.0.0.1 localhost
127.0.0.1 localhost.thisCompany.com
And then I have been told that I should be able access my webapp at http://localhost.thisCompany.com.
I am using node express as my server and the code in my server.js file looks like this
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 'thisCompany.com';
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
Can anyone advise what steps I should follow to enable me to call this API and bypass the API CORS policy?
I have read various other posts here, and also other articles online, however I cannot find the solution. Really hoping someone on this can help.
Thanks, Paul
I misunderstood how I was supposed to view a page locally on my computer after amending the hosts file on my local machine. I didn't need to add anything to my express server. The express server code remained as follows:
var express = require('express');
var server = express();
var path = require('path');
var port = process.env.PORT || 3000;
server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));
server.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/views/index.html'));
});
server.listen(port, function() {
console.log("Node app is running at localhost:" + port)
});
After adding the line mentioned in my original post to my hosts file on my local machine, I then needed to launch my server and access the page by following this link.
http://localhost.thisCompany.com:3000/
Although this is quite a niche issue, I hope this post helps someone in the future.

Socket Hang Up when using https.request in node.js

When using https.request with node.js v04.7, I get the following error:
Error: socket hang up
at CleartextStream.<anonymous> (http.js:1272:45)
at CleartextStream.emit (events.js:61:17)
at Array.<anonymous> (tls.js:617:22)
at EventEmitter._tickCallback (node.js:126:26)
Simplified code that will generate the error:
var https = require('https')
, fs = require('fs')
var options = {
host: 'localhost'
, port: 8000
, key: fs.readFileSync('../../test-key.pem')
, cert: fs.readFileSync('../../test-cert.pem')
}
// Set up server and start listening
https.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
// Wait a second to let the server start up
setTimeout(function() {
var clientRequest = https.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
}, 1000)
I get the error even with the server and client running on different node instances and have tested with port 8000, 3000, and 443 and with and without the SSL certificates. I do have libssl and libssl-dev on my Ubuntu machine.
Any ideas on what could be the cause?
In
https.createServer(function (req, res) {
you are missing options when you create the server, should be:
https.createServer(options, function (req, res) {
with your key and cert inside
I had a very similar problem where the response's end event never fired.
Adding this line fixed the problem:
// Hack to emit end on close because of a core bug that never fires end
response.on('close', function () {response.emit('end')});
I found an example of this in the request library mentioned in the previous answer.
Short answer: Use the the latest source code instead of the one you have. Store it where you will and then require it, you are good to go.
In the request 1.2.0 source code, main.js line 76, I see
http.createClient(options.uri.port, options.uri.hostname, options.uri.protocol === 'https:');
Looking at the http.js source code, I see
exports.createClient = function(port, host) {
var c = new Client();
c.port = port;
c.host = host;
return c;
};
It is requesting with 3 params but the actual function only has 2. The functionality is replaced with a separate module for https.
Looking at the latest main.js source code, I see dramatic changes. The most important is the addition of require('https').
It appears that request has been fixed but never re-released. Fortunately, the fix seems to work if you just copy manually from the raw view of the latest main.js source code and use it instead.
I had a similar problem and i think i got a fix. but then I have another socket problem.
See my solution here: http://groups.google.com/group/nodejs/browse_thread/thread/9189df2597aa199e/b83b16c08a051706?lnk=gst&q=hang+up#b83b16c08a051706
key point: use 0.4.8, http.request instead of http.createClient.
However, the new problem is, if I let the program running for long time, (I actually left the program running but no activity during weekend), then I will get socket hang up error when I send a request to http Server. (not even reach the http.request). I don't know if it is because of my code, or it is different problem with http Server