Pass data from client to server. Express - node.js

i'm little stuck on my express application.
I have a file index.js in routes folder and I want to save the result of mydata
var express = require('express');
var router = express.Router();
router.get('/', token, function(req, res, next) {
var mydata = req.userId
res.render('index', {
title: 'Welcolme',
});
});
module.exports = router;
And, in my other file (which depends on app.js), I would like to get and pass mydata to the server
var app = require('../app');
server.listen(port, function () {
require('../assets/js/server/socket')(server, mydata);
});
(Here is my app.js)
var express = require('express');
var indexRouter = require('./routes/index');
var path = require('path');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');
app.use('/', indexRouter);
module.exports = app;
And the socket file
var io = {};
module.exports = (server, mydata) => {
console.log('Hello : ' , mydata)
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('Connected')
});
};
Is there a way to do that?
Thank you :)

Maybe instead of still having this route.get('/') ...
You can let the user enter the data and have it transferred directly through the WebSocket connection.
Example:
//Client-side
//Get the user data somewhere from the HTML page
const userData = document.getElementbyId("some html element's id here").innerHTML;
//Send it to the back end
socket.emit('userData',userData)
//Open a listener to get the data from the back end later
socket.on('processedData',processedData=>{
//Use it in the way you desired.
});
//Server-side
io.on('connection', (socket) => {
console.log('Connected')
socket.on('userData',userData=>{
//Do something here, like validation and stuff
socket.emit('processedData','processedData here')
});
});

Related

Node.js how to use socket.io in express route

In one of my node.js script i am trying to use socket.io in express route. I found many similar questions and tried to implement the solution as suggested but nothing worked out. May be because of my lack of understanding of express routes. I followed below links,
How use socket.io in express routes with node.js
Use socket.io in expressjs routes instead of in main server.js file
This is my app.js
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const PORT = 3000;
server.listen(PORT);
console.log('Server is running');
var api = require('./routes/api');
//app.use('/api', api);
app.use('/api', (req, res) => {
res.sendFile(__dirname + '/api.html');
});
app.get('/', (req, res) => {
res.send("this is home location");
});
And route file api.js in ./routes folder
var express = require('express');
var router = express.Router();
var fs = require("fs");
var bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
console.log("inside api route");
router.get('/', function(req, res, next) {
console.log("api route called");
const connections = [];
var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]
io.sockets.on('connection',(socket) => {
connections.push(socket);
console.log(' %s sockets is connected', connections.length); // this is not printing
socket.on('disconnect', () => {
connections.splice(connections.indexOf(socket), 1);
});
socket.emit('server message', jsonobj);
});
//res.send(jsonobj)
});
module.exports = router;
Socket.emit is not showing data on html page i am rendering on route use. My html code is,
//api.html
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<h1 class="jumbotron">
Node js Socket io with socket route example
</h1>
<div class="results">results</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
jQuery(document).ready(function() {
var socket = io.connect();
var jsondata = "";
socket.on('server message', function(data){
console.log('got data from server',data)
jsondata = JSON.stringify(data);
//console.log('jsondata',jsondata)
$('.results').html(jsondata);
});
});
</script>
</body>
</html>
Please suggest what i am supposed to get route socket data in html page.
Thanks
Ok, let's try to understand why do you need to send data via the socket inside a route in the first place. Websockets are meant for sending data asynchronously without the client having to make a request. If the client is already making an HTTP request, then you can just send the data in the HTTP response.
Now having said there, there are clearly some use cases where you have to send data to some WebSocket channel based on the actions of some OTHER user's requests. If that is the case, there are multiple ways of doing this. One clean way would be to use an event-driven architecture.
Try something like this... find my comments inline below -
const express = require('express');
const router = express.Router();
const fs = require("fs");
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
// move the socket connection outside of the route controller
// you must register the event listeners before anything else
const connections = [];
io.sockets.on('connection', (socket) => {
connections.push(socket);
console.log(' %s sockets is connected', connections.length); // this is not printing
socket.on('disconnect', () => {
connections.splice(connections.indexOf(socket), 1);
});
});
// Event emitter for sending and receving custom events
const EventEmitter = require('events').EventEmitter;
const myEmitter = new EventEmitter();
myEmitter.on('my-event', function (jsonobj) {
// do something here like broadcasting data to everyone
// or you can check the connection with some logic and
// only send to relevant user
connections.forEach(function(socket) {
socket.emit('server message', jsonobj);
});
});
router.get('/some-route', function (req, res, next) {
const jsonobj = [{ name: "john", score: 345 }, { name: "paul", score: 678 }]
// emit your custom event with custom data
myEmitter.emit('my-event', jsonobj);
// send the response to avoid connection timeout
res.send({ok: true});
});
module.exports = router;
At first glance, it looks like you are delcaring the URL prefix twice. Once in app.js and again in api.js.
Try localhost:port/api/api
If this is the case, change
router.get('/api', function(req, res, next){
to
router.get('/', function(req, res, next){
This will allow you to hit localhost:port/api and access your endpoint.
I am just starting to understand this myself, but I think where you are at is close.
In your app.js add to the end of the file:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const PORT = 3000;
server.listen(PORT);
console.log('Server is running');
var api = require('./routes/api');
//app.use('/api', api);
app.use('/api', (req, res) => {
res.sendFile(__dirname + '/api.html');
});
app.get('/', (req, res) => {
res.send("this is home location");
});
app.set("socketio", io); // <== this line
That stores the "io" variable in "socketio". Which you can grab in any of your other ".js" files.
var express = require('express');
var router = express.Router();
var fs = require("fs");
var bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
//const io = require('socket.io').listen(server); // <== change this
const io = app.get("socketio"); // <== to this
console.log("inside api route");
router.get('/', function(req, res, next) {
console.log("api route called");
const connections = [];
var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]
io.sockets.on('connection',(socket) => {
connections.push(socket);
console.log(' %s sockets is connected', connections.length); // this is not printing
socket.on('disconnect', () => {
connections.splice(connections.indexOf(socket), 1);
});
socket.emit('server message', jsonobj);
});
//res.send(jsonobj)
});
module.exports = router;
And you should do that with any other variables which are required in other ".js" files.
Also note that in your files, you are setting the variables up again. It is better to do the same as I've shown you with "io". The only variable in other files I setup is "app" itself.
Hope this helps...
You tried to create and start the servers from two different places in your single project, which is inconvenient. You just need some cleanup, that's all.
app.js
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
// Listen to sockets here instead of listening in routes/api.js
const connections = [];
var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]
io.sockets.on('connection',(socket) => {
connections.push(socket);
console.log(' %s sockets is connected', connections.length); // this is not printing
socket.on('disconnect', () => {
connections.splice(connections.indexOf(socket), 1);
});
socket.emit('server message', jsonobj);
});
const PORT = 3000;
server.listen(PORT);
console.log('Server is running');
var api = require('./routes/api');
//app.use('/api', api);
app.use('/api', (req, res) => {
res.sendFile(__dirname + '/api.html');
});
app.get('/', (req, res) => {
res.send("this is home location");
});
routes/api.js
var express = require('express');
var router = express.Router();
var fs = require("fs");
var bodyParser = require('body-parser');
// Comment these out
// const app = express();
// const server = require('http').createServer(app);
// const io = require('socket.io').listen(server);
console.log("inside api route");
router.get('/', function(req, res, next) {
console.log("api route called");
// Comment these out
// const connections = [];
// var jsonobj = [{name:"john",score:345},{name:"paul",score:678}]
// io.sockets.on('connection',(socket) => {
// connections.push(socket);
// console.log(' %s sockets is connected', connections.length); // this is not printing
// socket.on('disconnect', () => {
// connections.splice(connections.indexOf(socket), 1);
// });
// socket.emit('server message', jsonobj);
// });
//res.send(jsonobj)
});
module.exports = router;
Leave your api.html as it is. Hope this helps.

NodeJS socket.io in a router page

I have the app.js code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('newRideAdded', function(exclude){
io.emit('newRideAdded', exclude);
});
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(__dirname + '/public/'));
app.use('/rides', require('./routes/rides'));
app.use('/user', require('./routes/user'));
server.listen("8080", function() {
console.log("Connected to db and listening on port 8080");
});
And I want to move the socket io code to its router's page.
That is the router page:
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs("ride4you", []);
router.post('/getRides', function(req, res, next) {
db.rides.find(function(err, docs) {
res.json(docs);
});
});
// rest of the restapi in this page.
// I want socket code to be here
module.exports = router;
As you can see i have each socket emits in each router's page and I already have module.exports in routers page.
How can it be done?
Thanks.
Using Express 4, in your app.js file you can use
app.set('socketio', io);
Then in your router or controller, you can use
router.post('/getRides', function(req, res, next) {
var io = req.app.get('socketio');
io.to(//socket.id//).emit("message", data);
db.rides.find(function(err, docs) {
res.json(docs);
});
};
This is a clean way of passing the reference along.

ExpressJS + Socket.IO Routing

Repeated Question, But i found no perfect answer as a solutions. Please help me to solve this issue.
My App.js
var routes = require('./routes/index');
var users = require('./routes/users');
var media = require('./routes/media');
var widget = require('./routes/widget');
var display = require('./routes/displays');
var device = require('./routes/deviceinfo');
app.use('/', routes);
app.use('/display', display);
var server = http.createServer(app);
var io = require('socket.io')(server);
io.set('transports', ['polling', 'websocket']);
Display Routes: "routes/display.js"
I have code to insert a display, As soon a display is created an event should emit to the list of devices.
Emit should need to write in save success callback Method.
var express = require('express');
var router = express.Router();
router.post('/save', action_save_displays);
function action_save_displays(req, res){
display.save(req,body , function(err , display){
if(!err){
res.json(display);
//io.sockets.emit("displaycreated", display);
}
})
}
module.exports = routes;
How to pass io.sockets.emit in routes/display.js file. really appreciate your guidance. how to send socket object to routes to enable emit event.
You can swap the requires around a bit, and just pass socket.io to the display.js file
var routes = require('./routes/index');
var users = require('./routes/users');
var media = require('./routes/media');
var widget = require('./routes/widget');
var server = http.createServer(app);
var io = require('socket.io')(server);
var display = require('./routes/displays')(io); // here
var device = require('./routes/deviceinfo');
app.use('/', routes);
app.use('/display', display);
io.set('transports', ['polling', 'websocket']);
and get it in the display.js file
var express = require('express');
var router = express.Router();
module.exports = function(io) {
router.post('/save', function(req, res) {
display.save(req.body , function(err, display){
if(!err){
res.json(display);
io.sockets.emit("displaycreated", display);
}
});
});
return router;
}

separate logic from view with route

I'm pretty new to Node and I'm using express.
I'm trying to implement simple file explorer.
enough talking here's some code:
(root dir is /app for this ex.)
my app.js:
var express = require('express');
var fs = require('fs');
var path = require('path');
var ejs = require('ejs');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var explorer = require('./routes/explorer');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use("/public", express.static(__dirname + '/public'));
app.use('/', explorer);
server.listen(3000,function(){
console.log('Server started on http://localhost:3000');
});
io.on('connection',function(client){
console.log('connection with io established');
});
module.exports.app = app;
module.exports.server = server;
see that I have routing '/' to explorer
and the explorer.js:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function(req, res, next) {
res.render('explorer',{
currentPath : currentPath
});
});
function getUserHome() {
var rawPath = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
return rawPath;
}
function clicked(){
console.log(getUserHome());
}
the view explorer.ejs:
<div class="clickable">clickme</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
socket.emit('clicked');
});
</script>
basically i want to catch the "clicked" emit from the view and trigger the clicked function in the explorer.js. in other words i want the view and the explorer.js talk by socket.io, so the view can talk with the file system.
i tried few way and got bunch of error.
thank you so much!
So you've triggered the event 'clicked' on your client side :
// Client side :
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
socket.emit('clicked');
});
Now, you have to catch it on the server side, in the explorer.js file :
// Server side :
// Instanciate your socket.io on the server side
var io = require('socket.io')(server)
// Listen for a client connection :
io.sockets.on('connection', function(socket){
// Inside the connection, you can now declare each function for each event triggered on the client side
socket.on('clicked', function() {
// This is your callback,
//+ the code in this scope will be executed
//+ only when the event 'clicked' is emitted
cliked();
});
});

Node/Express.js request handling with different files

//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.
app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};
How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);

Resources