Using socket io with express and ejs - javascript

Hey so i just started to learn node js today and i am using express with ejs and trying to add a socket io server / chat but i can't seem to work out why i can't get it to work.
The page loads but does not connect to the socket server.
server.js:
const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const app = express();
// EJS
app.use(expressLayouts);
app.use(express.static("public"));
app.set('view engine', 'ejs');
// Routes
app.use('/', require('./routes/index.js'));
app.use('/chat', require('./routes/chat.js'));
app.use((req, res, next) => res.redirect('/'));
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port)
});
routers/chat.js
const express = require('express');
const router = express.Router();
const server = require('http').createServer();
const io = require('socket.io')(server);
// Chat Page
router.get('/chat', (req, res) => {
res.render("chat/chat");
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
});
});
module.exports = router;
views/chat/chat.ejs:
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
Error:
Uncaught ReferenceError: io is not defined

You cannot source /socket-lib/socket.io.js,
you must source http://yourwebsite.com:12345/socket.io/socket.io.js.
bascily, you'll need to provide full source for the server adress.
The server automatically does the rest for you.
Source: https://stackoverflow.com/a/12160485/3010171
also. you might try out ./socket-lib/socket.io.js with a . before the slash

Related

Node js with express and socket.io -can't fint socket.io.js

So basically what i am trying to do is build a chat app with a login system but for some reason i cant put it together and i am getting an error when i join to the room the chat.hbs can't find the socket.io.js file and also the main.js is getting a reference error with the const socket = io(); (the chat app works fine without the login system)
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not definedat main.js:11
This is the app.js file
const express = require("express");
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = "Bot";
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(cookieParser());
app.set('view engine', 'hbs');
//eldönti az útvonalat
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
This is the main.js
const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');
// Felhasználó név és szoba név URL-ből
const { username, room } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const socket = io();
// Csatlakozik chat szobába
socket.emit('joinRoom', { username, room });
// Lekérdezi a szobát felhasználókat
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
And the chat.hbs
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
Well the problem was that I used:
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
instead of:
server.listen(5001, () => {
console.log("Server started on Port 5001");
})
Szia, you will need to wait for the DOM to load.
window.addEventListener('load', function () {
// Your code goes here
const socket = io();
socket.on("connect", () => {
// you can only emit once the connection is established.
socket.emit('joinRoom', { username, room });
});
})

Passing a Socket.IO instance to route files

I am looking to share the a socket.io instance with my express route files.
I previously had the socket.io listener in one routes file, orders.js on port 5200 and the express server listening in app.js on port 5000, however my cloud service required me to use one port for both, so I did have moved them both to app.js. The code below has been drastically simplified to remove noise
./app.js
const port = process.env.PORT || 8000;
const socket = require('socket.io');
const server = app.listen(port, () => console.log(`[!] Listening on
port: ${chalk.green(port)}`))
const io = module.exports = socket(server);
app.use(express.json());
app.use(cors());
app.use('/', router)
./routes/index
const express = require('express');
const router = express.Router();
router.use('/orders', require('./orders'));
module.exports = router;
./routes/orders.js
const express = require('express');
const router = express.Router();
const io = require('../index');
io.on('connection', (client) => {
console.log("CLIENT CONNECTED");
})
router.get(... etc etc
I expect to get a connection console but instead I'm getting an error that IO is not a function. When I console.log(io) I get {}
Try this way
const user = require('{SET FILE PATH}');
io.on('connection', function (socket) {
console.log('Socket connected...', socket.id);
socket.on('login', function (req) {
user.login(socket, req, 'login'); // socketObj , req , methodName
})
});
user.js
class User {
login(socket, req, methodName) {
console.log("Socket ref is ::: " , socket);
}
}
module.exports = new User();

Socket.IO & Node/Express Configuration

I am trying to connect my front-end which is on a online text editor to my Node server. I am hitting network error strict-origin-when-cross-origin and it is not hitting the Socket IO listener. Please let me know what is causing this error & how to fix it. Thanks!
Here is the Node.js code:
const cors = require('cors');
const app = express();
app.options('*', cors())
app.all('*', function(req, res) {
res.send("Oops, incorrect URL")
});
const server = http.createServer(app).listen(process.env.PORT, () => {
console.log('Express server listening on port 1337');
});
var io = require('socket.io')(server);
io.set('origins', '*:*');
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
console.log("CONNECTED!")
});
Here is the front-end:
import io from 'socket.io-client'
var socket = io('https://myserver.com/', {secure: true});
socket.emit('chat message', "testing");

socket.io not working with node server

I'm trying to set up my node server to update all the connected clients with new information in real-time. When I run the code below, the io.sockets.on('connection') callback is fired constantly, flooding the console with the message Client connected!, and the front-end is not being updated from socket.emit(). What am I doing wrong?
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var models = require('./models.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
// Connect to the Mongo database
mongoose.connect('mongodb://localhost/test');
bin/www.js
#!/usr/bin/nodejs
var debug = require('debug')('my-application');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function(data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
public/javascripts/update.js
var socket = io.connect('http://' + document.location.hostname + ':3000/');
socket.on('connect', function() {
console.log('Socket connected!');
socket.emit('message', 'Message from client');
});
socket.on('update', function(data) {
alert(data);
});
And when I end the npm process, the client begins to log
http://<ip>:3000/socket.io/?EIO=2&transport=polling&t=1498772846992-691 net::ERR_CONNECTION_REFUSED
I've read posts about the express router messing with the socket requests but I can't seem to get it working no matter what I try.
Can you try this setup?
EDITED:
app.js:
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function (req, res) {
res.render('index');
});
module.exports = app;
bin/www.js:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000', function () {
console.log('server listens on port 3000');
});
var io = require('socket.io')(http);
io.listen(server);
io.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function (data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
index.pug (or jade, they say jade is obsolete):
doctype html
html
body
h1 Testing socket.io
h3#status not connected
br
p#update update:&nbsp
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
socket.emit('message', 'Hello!');
});
socket.on('update', function (data) {
document.getElementById("update").innerHTML += data;
});
Calling app.listen (where app is the result of invoking express()) returns an HTTPServer, which can be used to setup the socket connection:
var server = app.listen(port);
var io = socket(server);
without manually running your solution, I'd guess that because you're creating a new HTTPServer to be feed into the socket, it's somehow getting hung in a loop.

node.js not printing to console

I am trying to use sockets in my api. However I could not see the logs in the console.
The only output I see is:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
We are live on8000
Here is my server.js file:
// server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const db = require('./config/db');
app.use(express.static(__dirname + '/../app'));
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url,(err,database) =>{
if (err) return console.log(err);
//check below line changed
require('./app/routes')(app, database);
app.listen(port,() => {
console.log("We are live on"+port);
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket){
console.log('client connected');
socket.on('disconnect', function () {
console.log('disconnect');
});
});
})
and the index.html is:
<!DOCTYPE html>
<html>
<head><title>Hello world</title></head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>Hello world</body>
</html>
I see Hello world on the web browser, but I could not see 'client connected' on the console log.
Update: In your browser client you can see error in console.log http://localhost:8000/socket.io/socket.io.js 404 and (index):6 Uncaught ReferenceError: io is not defined
You have attach socket handler to a http server var io = require('socket.io')(server);, but in your code you start web server by express server
app.listen(port,() => {
console.log("We are live on"+port);
});
change it to
server.listen(port,() => {
console.log("We are live on"+port);
});
I have created a new .js file and listening to port 3000 instead of 8000 worked for socket.io
appsocket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket){
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Now I am able to see the logs on console when I call localhost:3000 instead of localhost:8000

Categories