Track click event through socket.io - node.js

I am developing a node.js application with express and socket.io to track click event from users .. my code snippet is
app.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/user.html');
});
app.get('/admin', function(req, res){
res.sendFile(__dirname + '/admin.html');
});
io.on('connection', function(socket){
socket.on('clicked', function(val){
io.emit('clicked', val);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
user.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
</style>
<title></title>
</head>
<body>
<button id="click">Click Me</button>
<script>
var socket = io('http://localhost:3000');
var count = 0;
$('#click').click(function(){
var val = count++;
socket.emit('clicked', val);
});
</script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</body>
</html>
admin.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Total no. of clicks</h2>
<p id="message"></p>
<script>
var socket = io('http://localhost:3000');
socket.on('clicked', function(val){
console.log(val);
$('#message').text(val);
});
</script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</body>
</html>
All I want to do is display no. of clicks on the admin page in realtime
Error I got in admin page through console is

//Put your javascript code below these two libraries
<script src="https://cdn.socket.io/socket.io-1.2.0.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
<script type="text/javascript">
var socket = io('http://localhost:3000');
socket.on('clicked', function(val){
console.log(val);
$('#message').text(val);
});
</script>

Related

Cannot Make a To-Do-List app using Ejs Templating

I'm doing a full stack web dev course. I follow along the instructor, but he was able to put bullet points upon HTML form input but I can't. There are some unnecessary code from previous lectures. But here is my code:
list.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
</head>
<body>
<h1>
<%= kindOfDay %>
</h1>
<ul>
<li>Buy Ganja</li>
<li>Roll Ganja</li>
<li>Smoke Ganja</li>
<% for(var i=0;i<newListItems.lenth; i++){ %>
<li> <%= newListItems[i] %></li>
<% } %>
</ul>
<form action="/" method="post">
<input type="text" name="newItem">
<button type="submit" name="button">Add</button>
</form>
</body>
</html>
And here is my server file:
App.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
var items = [];
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", function (req, res) {
var today = new Date();
var options = {
weekday: "long",
day: "numeric",
month: "long",
};
var day = today.toLocaleDateString("en-US", options);
res.render("list", { kindOfDay: day, newListItems: items });
});
app.post("/", function (req, res) {
var item = req.body.newitem;
items.push(item);
res.redirect("/");
});
app.listen(3000, function () {
console.log("Server Started at Port 3000");
});
Here is the screenshot. I cannot add extra points upon form submission!
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(express.urlencoded({extended:true}));
app.get("/",function(req,res){
var today = new Date();
var options = {
weekday: "long",
year:"numeric",
day: "numeric",
month:"long"
};
var day = today.toLocaleDateString("en-US",options);
res.render("index",{kindOfDay:day,tasks:tasks});
})
var tasks = [];
app.post("/",function(req,res){
const task = req.body.newItem;
tasks.push(task);
res.redirect("/");
})
app.listen(3000,function(){
console.log("Server is running");
})
<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>To-Do List App</title>
</head>
<body>
<h1><%= kindOfDay %> </h1>
<ul>
<li>Buy Food</li>
<li>Watch Movies</li>
<% for(var i=0;i<tasks.length;i++){ %>
<li><%= tasks[i] %> </li>
<% } %>
</ul>
<form action="/" method="POST">
<label for="newItem">Add New Task</label>
<input type="text" name="newItem" id="newItem">
<button type="submit">Add</button>
</form>
</body>
</html>

Socket.IO not connecting from web browser

I am trying to build live location tracking using socket and nodejs
but i am unable to connect to websocket using socket.io below is the code of node js server
const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');
var app = require('express')();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var options = {
key: fs.readFileSync('path.pem'),
cert: fs.readFileSync('path/cert.pem'),
ca: fs.readFileSync('path/cert.pem'),
requestCert: true,
rejectUnauthorized: false
};
var io = require('socket.io')(https, {
cors: {
origin: "https://aayo.express:3000",
methods: ["GET", "POST"]
}
});
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');
setTimeout(function() {
//Sending an object when emmiting an event
socket.emit('testerEvent', { description: 'A custom event named testerEvent!'});
}, 4000);
socket.on('clientEvent', function(data) {
console.log(data);
});
//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');
// });
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
console.log(req);
console.log('listening on *:3000');
}).listen(3000);```
below is my html file
#extends(backpack_view('blank'))
#section('after_styles')
<!-- Web Fonts
================================================== -->
<link href="https://fonts.googleapis.com/css?family=Muli:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"/>
<!-- CSS
================================================== -->
<link rel="stylesheet" href="{{asset('frontend/css/bootstrap.min.css')}}"/>
<link rel="stylesheet" href="{{asset('frontend/css/font-awesome.min.css')}}"/>
<link rel="stylesheet" href="{{asset('frontend/css/ionicons.min.css')}}"/>
<!-- <link rel="stylesheet" href="{{asset('frontend/css/owl.carousel.css')}}"/>
<link rel="stylesheet" href="{{asset('frontend/css/owl.transitions.css')}}"/>
<link rel="stylesheet" href="{{asset('frontend/css/style.css')}}"/> -->
#endsection
#section('content')
<div class="loader">
<div class="loader__figure"></div>
</div>
<!-- Nav and Logo
================================================== -->
<iframe src="https://aayo.express:3000"></iframe>
<!-- Primary Page Layout
================================================== -->
<div class="section full-height over-hide">
<div id="map" class="" style="width:100%;height:600px;"></div>
<div class="tracking-info">
<ul>
<li><b>Driver Name: </b> Subash Rijal </li>
<li><b>Phone no.</b> 0123456789</li>
<li><b>Distance: </b> 5km</li>
</ul>
</div>
</div>
<!-- Modal -->
#endsection
#section('after_scripts')
<!-- JAVASCRIPT
================================================== -->
<script src="{{asset('frontend/js/jquery.min.js')}}"></script>
<script src="{{asset('frontend/js/popper.min.js')}}"></script>
<script src="{{asset('frontend/js/bootstrap.min.js')}}"></script>
<script defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCcI96mdv1eVkGj4p3L61Xyri_SFUNA3xI&callback=initMap"></script>
<script src="{{asset('frontend/js/plugins.js')}}"></script>
<!-- <script src="https://cdn.socket.io/3.0.5/socket.io.min.js'"></script> -->
<script src="{{asset('js/socket.io.js')}}"></script>
<script src="{{asset('js/live-location.js')}}"></script>
<script src="{{asset('frontend/js/custom.js')}}"></script>
<script>
function initMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map = new google.maps.Map(document.getElementById("map"),mapProp);
}
</script>
<script>
</script>
<!-- End Document
================================================== -->
#endsection
how can i solve this? i am using nodejs, and server code to run it
if you have any experience in it could you please help me to solve this?
thanks in advance

ExperimentalWarning: Conditional exports is an experimental feature"

I am getting this in error in node js while running a server. The error is as follows
"(node:17160) ExperimentalWarning: Conditional exports is an
experimental feature". This feature could change at any time"?
Full details can be found here
Any idea how to solve this? I am getting it in the terminal while running the nomemon server.js. My codes are as follows:
Here is mine:
Server.js
const express = require('express')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const { v4: uuidV4 } = require('uuid')
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res) => {
res.redirect(`/${uuidV4()}`)
})
app.get('/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).broadcast.emit('user-connected', userId)
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
})
server.listen(3000)
script.js
const socket = io('/')
const myPeer = new Peer(undefined, {
host:'/',
port:'3002'
})
myPeer.on('open', id => {
socket.emit('join-room', ROOM_ID, id)
})
socket.emit('join-room', ROOM_ID, 10)
socket.on('User-connected', userId => {
console.log('User-connected:' + userId)
})
Room.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Just Not a Document</title>
<script>
const ROOM_ID = "<%= roomId %>"
</script>
<script defer src="https://unpkg.com/peerjs#1.3.1/dist/peerjs.min.js"></script>
<script src="/socket.io/socket.io.js" defer></script>
<script src="script.js" defer></script>
<style>
#video-grid {
display: grid;
grid-template-columns: repeat(auto-fill, 300px);
grid-auto-rows: 300px;
}
video {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div id="video-grid"></div>
</body>
</html>

ace editor is not working in socket.io node app

In my Socket app, I'm trying to send programming code as a message to another client. If run the HTML only it shows the Ace editor perfectly. But when I run node app.js the ace editor doesn't work.I have downloaded ace-builds and installed npm ace-code-editor in the app, but nothing changes here is my code
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
);
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
})
socket.on('chat message', function (msg) {
console.log("message: " + msg);
io.emit('chat message', msg);
});
});
http.listen(port, function () {
console.log('listening on *:' + port);
});
index.html
<html>
<head>
<title>Socket.IO </title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#m {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<script src="/ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var editor = window.ace.edit("m");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/javascript");
$(function () {
var socket = io();
var myvar = setInterval(task, 100)
function task() {
var code=editor.getValue();
socket.emit('chat message',code);
}
socket.on('chat message', function (msg) {
editor.setValue("the new text here");
});
});
</script>
</head>
<body>
<div id="m">function foo(items) {
var x = "All this is syntax highlighted";
return x;
} </div>
</body>
</html>
Need a solution
you are calling window.ace.edit("m"); before that element becomes available.
Move script tag to the end of the file, or move ace initialization into $ call.

Examples not returning message to client

I am trying to follow this example, but I don't see the message "Hello World from client" on the brower. For that matter, I don't see the Client connected....
I do see the Hello World and the form .
app.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
client.emit('messages', 'Hello from server');
});
});
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
index.html
<!doctype html>
<html lang="en">
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
<head>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="form" id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
<script> tag just could resides in <head> or <body> tags. If you are going to manipulating the dom and not using a DomReady function to check whether the dom is ready or not, then you should place all your script tags at the end of your body tag just before </body>:
<!doctype html>
<html lang="en">
<head>
<title>My App</title>
</head>
<body>
<h1>Hello World!</h1>
<div id="future"></div>
<form id="chat_form">
<input id="chat_input" type="text">
<input type="submit" value="Send">
</form>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:4200');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
socket.on('messages', function(data) {
alert(data);
});
</script>
</body>
</html>

Resources