NodeJS - Socket.io Connection to Routes - node.js

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);

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;

App.route is not a function when accessing it in a controller function for express routing

I am trying to create a simple API using NodeJS.
I plan to separate the main api.js, route-definitions.js, route-logic.js in their own separate folders for them to be more structured and organized.
However, when I call app.route() in my route-definitions.js, it fails at compilation and saying that app.route is not a function.
server.js
var express = require('express')
var api = require("./api/api.js");
app = express();
port = process.env.PORT || 3000;
app.use('/', api);
app.listen(port);
api.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions'));
module.exports = router;
route-definitions.js
'use strict';
module.exports = function(app) {
var operations = require('../controllers/route-logic.js')
//Route to check if a file with the same file name already exists
app.route('/getItems')
.post(operations.getItems);
}
When I try to run the API locally, and call /read/getItems, I get the error:
TypeError: app.route is not a function
What am I missing? I'm fairly new to Node and Express, but I know I'm not passing the app instance correctly or it is not set globally.
You can solve it by creating a child router in route-definitions.js
var router = require('express').Router();
var operations = require('../controllers/route-logic.js');
router.post('/getItems', operations.getItems);
module.exports = router;
In api.js you need to pass the router to the function you are exporting in route-definitions.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions')(router));
module.exports = router;
You've used app in the route-definitions.js but looks like you forgot to pass it to that module.
Please have a look at below code:
var express = require('express');
var router = express.Router();
var app = express();
router.use('/read', require('./routes/route-definitions')(app));
module.exports = router;

socket.io and express routing - how to setup

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?

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");
};

NodeJS Require, where do I use this?

Node JS require for the bittrex api... exactly where do it.
npm everything is installed including require...
var bittrex = require('bittrex-api');
on any page gives require is not defined
1) I'm using ui-router, server.js is not needed... I added one anyway.
var express = require('express');
var path = require('path');
//var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//var bcrypt = require('bcryptjs');
var app = express();
app.set('port', process.env.PORT || 8080);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
now I want to add the bittrex ticker on the dashboard... so on the dashboard view I add
var market = 'BTC-LTC';
var bittrex = require('bittrex-api');
I turn on the server.js file and I get the require undefined message, I turn it off same message.
What am I doing wrong?

Resources