Use socket.io across diffrent routes in node.js - javascript

I have different routes in my node js application and now i want to use socket.io in every route to make my node and react js application realtime. But, i have the below structure of my node js application.
router.js
const express = require('express');
const router = express.Router();
const worksheetController = require('../controllers/worksheet');
const attendenceController = require('../controllers/attendence');
router.route('/worksheets')
.get(
worksheetController.getWorksheet
)
.post(
worksheetController.validateWorksheet,
worksheetController.addWorksheet,
attendenceController.markAttendence
);
router.route('/attendances')
.get(
attendenceController.getAttendance
);
module.exports = router;
server.js
const express = require('express');
const router = require('./router');
const app = express();
app.use('/api', router);
app.listen('5000', () => {
console.log('Listening on port');
});
module.exports = app;
How can I use socket.io for different routes?

You don't need to correlate express routes and socket.io events. They are two different things. Perhaps you can add the related logic in the controllers and call the functions from socket.io events as you have done with express routes.
eg:
const worksheetController = require('../controllers/worksheet');
io.on('connection', function (socket) {
socket.on('my event', function (data) {
const myData = worksheetController.getDataForOtherEvent(data);
console.log(myData);
});
});

Related

How to separate all of socket.io to a different file

Right now, I have app.js where I have my usual code and my socket.io code. But what I want to do is, separate every single code of socket.io into 1 different file and require that socket.io code from the different file into my main app.js. Is there any way to do it writing 2/3 lines of code into my app.js to require socket.io from a different file?
Note: I do not want to write any of my socket.io code into my app.js so I do not know if it would be possible to require('....') it into my app.js from a different file. Ideally want to separate everything within io.on('connection'){}
const express = require('express');
const http = require('http'); // socket.io is created upon http server. A way to create server
const cors = require('cors');
const {Server} = require('socket.io');
const app = express();
app.use(cors());
const server = http.createServer(app); // this is to create http server with express for socket.io
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
socket.on("newUser", (username) => {
addNewUser(username, socket.id);
console.log('connect print: '); printUsers();
})
socket.on("disconnect", () => {
removeUser(socket.id);
console.log('disconnect print: '); printUsers();
});
})
server.listen(3001, () => {
console.log('server listening on port 3001');
})
There would be a few way to do this but something like below should work.
In your new file, use module.exports to export an object containing any functions or objects you want to export:
//socketio.js
module.exports = {
getIo: (server) => {
const io = new Server(server, {
//...
});
io.on("connection", (socket) => {
//...
}
//your other functions
return io;
}
}
Then in your app.js, require it and use the object's properties:
//app.js
const socketio = require('./socketio.js');
//after creating your server etc
const io = socketio.getIo(server);

Why does my express router not respond to my get request?

So i have made a simple express app, but i have been trying for several hours to get a response to a simple get request when i visit http://localhost:3000/
This is my app.js
// IMPORTS
const express = require('express')
const mongoose = require('mongoose')
const customerRouter = require('./routes/customerRoute.js')
const app = express()
const PORT = 3000
// CONNECTION
mongoose.connect('mongodb://localhost/Customers', {useUnifiedTopology: true })
mongoose.connection.on('open', () => {console.log('Connected to database.')})
//APP USE ROUTES AND JSON
app.use(express.json)
app.use('/customers',customerRouter)
app.get('/', (req, res) => {
res.send('Home')
})
// APP PORT SET
app.listen(PORT)
console.log('Server started on port 3000')
This is my routes file
const express = require('express')
const router = express.Router()
console.log('into the router')
router.get('/', (req, res) => {
console.log('GET request')
})
module.exports = router
Substitute app.use(express.json) with app.use(express.json()) and everything will work. You have a mistake in this middleware that parses incoming requests with JSON payloads.
Source: express docs
You made a mistake in middleware app.use(express.json()) is a function not a property of the express object.

404 Cannot POST Using Express

I´m trying to create an API Rest in NodeJs with Express.
I have my index.js with the following code:
const express = require('express');
const routesV1 = require('./routes/v1/index');
const app = express();
routesV1(app);
app.listen(4000, () => {
console.log('Running on port: 4000');
});
then i have a routes folder with another "index.js" and a "usersRoutes".
Here´s the code of the userRoutes:
const express = require('express');
const userController = require('../../controllers/v1/UserController');
const router = express.Router();
router.post('/create', userController.createUser);
router.post('/update', userController.updateUser);
router.post('/delete', userController.deleteUser);
router.get('/get-all', userController.getUsers);
module.exports = router;
and the code of the index.js into the routes folder:
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('api/v1/users', userRoutes);
};
but when i´m consuming via Postman, with the following url: http://localhost:4000/api/v1/users/create I´m receiving a 404 error code.
Can anybody help me? thanks
I resolved it adding '/' to the route in routes/index.js
const userRoutes = require('./UserRoutes');
const productRoutes = require('./ProductRoutes');
module.exports = app => {
app.use('/api/v1/users', userRoutes);
app.use('/api/v1/products', productRoutes);
};

Is this the correct way to share a instance of a Redis client in Express?

Due to I have the application routes dedined in separated scripts I need a way to share the same Redis client across all of them. Is this the correct way of doing it ?
app.js
const express = require('express');
const app = express();
var redis = require("redis"),
client = redis.createClient();
app.use((req, res, next) => {
req.redis = client;
next();
});
// load routes
app.listen(3000, () => console.log('Example app listening on port 3000!'));
... other js file
app.get('/xyz', (req, res) => {
var redis = red.redis;
// use redis
});
You're un-necessarily passing your client instance to every request regardless of if it's needed.
I use a pretty standard controller which you can then require() as needed, example below.
var redis = require('redis')
.createClient(...);
redis.on('connect', function() {
console.log('Redis server online.');
});
module.exports = redis;
Then whenever you want to access it
var redis = require('./app/controllers/redis');
// redis => Redis client instance

redirect to different controller dependant on Url

Ok so I'm trying to redirect the request to a different controller depending on the URL.
My server.js :
const express = require('express');
var app = express();
var router = express.Router();
// controllers
var { loginController } = require('./controller/loginController');
// Specify routes
app.use('/test', loginController);
app.listen(3000, () => {
console.log('started on port 3000');
});
module.exports = { app }
Now if the URL is /test then I would like to redirect the request to loginController, inside loginController I have the following:
const express = require('express');
var router = express.Router();
router.get('/', (req, res) => {
res.send('inside logincontroller');
});
Very short and sweet, however when I run node server.js I get the following error message: Router.use() requires middleware function but got a undefined now I've gone through the Router Use but I'm slightly confused (newbie) I don't have any middleware at present.
Would someone be able to explain to me how I go about redirecting the request to the loginController when the url is /test
server.js
const express = require('express')
// Controllers
var loginController = require('./controller/loginController')
var app = express()
// Specify routes
app.use('/test', loginController)
app.listen(3000, () => {
console.log('started on port 3000')
})
loginController.js
const express = require('express')
var router = express.Router()
router.get('/', (req, res) => {
res.send('inside logincontroller')
})
module.exports = router
Then if you visit http://localhost:3000/test will get the output 'inside logincontroller'

Categories