socket.io and express routing - how to setup - node.js

I'm using:
express: v4.16.1
socket.io: v2.0.3
app.js
var express = require('express');
var app = express();
var io = require('socket.io').listen(app.listen(port));
var index = require('./index.js');
app.use('/', index);
io.on('connection', function(socket){//connection stuff});
Now every use of expres router in index.js:
var express = require('express');
var app = express();
var router = express.Router();
router.get('/seo', function(req, res){//page stuff here});
disconnect my established socket.io connection... How to pin socket to express router?

Related

Multiple Routes in node express backend

I am new in node js and want to build an application in which they are multiple APIs and all are settled in routes folder but here is the problem when I tried to call the API in index.js(main file) its only take one route either userAPI or cleanerAPI.
As both APIs have different URL.
var mongoose = require ('mongoose');
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const routerUser= require('./routes/userAPI')
mongoose.connect('mongodb://localhost:27017/Covid');
app.use(bodyParser.json());
app.use('/',router);
app.listen(4000,function(){
console.log("Server Running on 4000")
});
you can try this one also.
Main file(index.js or server.js)
const appRoutes = require('./Routes')
appRoutes(app)
Routes(index.js)
module.exports = app => {
app.use("/user", require('./users'));
app.use("/cleaner", require('./cleaner')); };
Routes(users.js)
const express = require('express');
const router = express.Router();
router.route('/list')
.post(function(req,res){......});
module.exports = router;

NodeJS - Socket.io Connection to Routes

I am trying to connect socket.io to my routing system, but despite the multiple methods I have read about to achieve this, I'm not sure the best approach with my setup as I have three degrees of separation from my server file and the route file that requires the socket.io configuration. Should I pass it as a constructor argument?
I tried passing the argument //Routing app.use(controllers)(io);, but ran into an error with the router module, so I don't believe I'm setting it correctly.
Error: var search = 1 + req.url.indexOf('?'); TypeError: Cannot read property 'indexOf' of undefined
Here is my setup.
app.js:
var express = require('express');
var app = express();
//Port Setting
var port = process.env.PORT || 3000;
//Server Port
var server = app.listen(port);
//External Packages
var io = require('socket.io')(server);
var redisAdapter = require('socket.io-redis');
var controllers = require('./app/controllers/routes');
//Routing
app.use(controllers);
routes.js:
var express = require('express');
var router = express.Router();
router.use('/app', require('./app-routes'));
router.use('/api', require('./api-routes'));
module.exports = router;
app-routes.js (where I would like to configure socket.io):
var express = require('express');
var app = express();
var appRoutes = express.Router();
/*==== / ====*/
appRoutes.route('/')
.get(activityFeed.load)
.post(activityFeed.filter);

Emitting and receiving events with Socket.io

I'm trying to emit an event with socket.io on my Node Js server and receive it client-side but I can't get it to work.
This is my server code:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = require("http").Server(app);
var io = require('socket.io')(server);
// use ejs and express layouts
app.set('view engine', 'ejs');
app.use(expressLayouts);
// use body parser
app.use(bodyParser.json({extended : true}));
// route our app
var router = require('./app/routes');
app.use('/', router);
// set static files (css and images, etc) location
app.use(express.static(__dirname + '/public'));
// start the server
app.listen(port, function() {
console.log('app started');
});
This is my routes.js code, where the magic should happen:
module.exports = function(io){
// require express
var express = require('express');
var path = require('path');
// create our router object
var router = express.Router();
// export our router
//module.exports = router;
router.post("/", function(request, response) {
console.log(request.body);
io.emit('getupdate',{hello:'world'});
});
// route for our homepage
router.get('/showevent', function(req, res) {
res.render('pages/showevent',{data:exportage});
});
return router;
}
While this is my client-side script:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('getupdate', function (data) {
console.log(data);
});
</script>
On the routes.js file, to get the "io" variable i wrapped all inside a function.
I can't get the message emitted in case of a POST request on my client.
Could you help me to find the issue here ?
Try this:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = app.listen(port);
var io = require('socket.io').listen(server);
I am not sure if you have updated this in your own code, but this snippet should pass io to the router:
// route our app
var router = require('./app/routes')(io);
app.use('/', router);

socket.io emit when someone call the API

I have a small project with NodeJS Express server and Angular2 frontend. The server has an API interfaces. The main part of this is: /api/alert. I want to do the following: If the /api/alert get an request then socket.io broadcast an event to all connected clients.
My server structure is the following:
server.js
var http = require('http'),
express = require('express'),
app = module.exports.app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
db = require('./config/db'),
path = require('path');
mongoose.Promise = global.Promise;
mongoose.connect(db.url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
var routes = require('./server/routes/index');
routes(app);
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(port);
console.log('Server started on: ' + port);
server/routes/index.js
const deviceRoute = require('./devicesRoute');
const alertRoute = require('./alertsRoute');
module.exports = function(app) {
deviceRoute(app);
alertRoute(app);
}
server/routes/alertRoute.js
'use strict';
module.exports = function(app) {
var alertsService = require('../services/alertsService');
app.route('/api/alert')
.post(alertsService.createAlert);
};
server/service/alertService.js
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
};
I can't pass the io and server variables to the function (from server.js). How can I do that? What is the easiest way?
Thank you!
First you would want to export both the app and server objects from server.js and pass your socket to your response in middleware as follows:
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
...
module.exports = {app: app, server: server};
You can then require the server instance you created in server.js (depending on where you are requiring it from) as
var server = require('../server').server;
Since you added socket.io to the response object, you can use it in your services as
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
res.io.emit("broadcast", "clients");
};

Package express-ws doesn't let clients connect

I have an express router defined for express-ws npm package. The router looks is exported like:
//ws.js
var express = require('express');
var router = express.Router();
var connections = {};
router.ws('/connect/', function (ws, req) {
// console.log(ws);
ws.on('close', function(x, y, z) {
console.log(a, b, c);
});
});
module.exports = router;
The (not all) statements in the express app are (and in order):
//app.js
var app = express();
var expressWs = require('express-ws')(app);
var index = require('./routes/index');
var ws = require('./routes/ws');
...
...
app.use('/ws', ws);
app.use('/*', index);
The server has statements like:
//bin/www - Generated by express generator
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
After I run it, I am not able to connect to /ws route over websocket. Am I missing something here? Is there a better way to create websocket running on Express 4?
This is the error I see at the client! What am I doing wrong?
changes to app.js
var app = express();
var server = require('http').Server(app);
var expressWs = require('express-ws')(app,server);
...
...
//module.exports = app;
module.exports = {app: app,server: server};
changes to bin/www
//var app = require('../app');
var app = require('../app').app;
...
...
//var server = http.createServer(app);
var server = require('../app').server;
I know this is old but here's the issue. HTTP server isn't required.
//app.js
const express = require('express');
const { app } = require('express-ws')(express());
const index = require('./routes/index');
const ws = require('./routes/ws');
...
app.use('/ws', ws);
app.use('/*', index);
...
app.listen(8080, () => console.log('Listening on port: 8080');

Resources