Socket.IO not connecting from web browser - node.js

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

Related

How to make the message automatically get other that reload page using socket.io, nodejs, and mongodb

I'm having a go with the socket.io https://socket.io/get-started/chat, but my problem is that when i send message then the message cant automatically into chat box. i need to reload the page to view the chat that i sent. So how to make the chat automatically insert to chat box?. i already implement into my project. i already used socket.emit as you can see at then html file. is there the right way to put it?
server.js
var express = require('express');
var env = require('dotenv').config()
var ejs = require('ejs');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session)
const cookieParser = require('cookie-parser')
var http = require('http').Server(app);
var io = require('socket.io')(http);
var cors = require('cors')
app.use(cors())
app.use(cookieParser());
// mongodb://localhost:27017 127.0.0.1:27017
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://127.0.0.1:27017/findaprofessional', {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if (!err) {
console.log('MongoDB Connection Succeeded.');
} else {
console.log('Error in DB connection : ' + err);
}
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
});
const oneDay = 1000 * 60 * 60 * 24;
app.use(session({
secret: 'work hard',
saveUninitialized:true,
cookie: { maxAge: oneDay },
resave: true
}));
// ni lain
app.set("view engine", "ejs")
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/css', express.static(path.resolve(__dirname, "asset/css")))
app.use('/img', express.static(path.resolve(__dirname, "asset/img")))
app.use('/js', express.static(path.resolve(__dirname, "asset/js")))
app.use('/vendor', express.static(path.resolve(__dirname, "asset/vendor")))
app.use('/lib', express.static(path.resolve(__dirname, "asset/lib")))
app.use('/scss', express.static(path.resolve(__dirname, "asset/scss")))
app.use('/pic', express.static(path.resolve(__dirname, "asset/img/pic")))
var index = require('./routes/index');
const { Socket } = require('socket.io');
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('File Not Found');
err.status = 404;
next(err);
});
// error handler
// define as the last app.use callback
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.send(err.message);
});
io.on('connection', () =>{
console.log('a user is connected')
io.on("disconnect", function () {
console.log("user disconnected");
});
})
var server = http.listen(3000, () => {
console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});
routing
// user chat
var http = require('http').Server(router);
var io = require('socket.io')(http);
// Render Message
router.get('/messages/:id', async function (req, res, next) {
user = await User.findOne({_id: req.session.userId}, {username: 1})
return res.render("user/messages.ejs", {user: user, booking: req.params.id});
});
// Display Message from DB
router.get('/messageslist/:booking', (req, res) => {
Message.find({booking: req.params.booking})
.populate({
path: "pro",
model: Pro,
}).populate({
path: "user",
model: User,
}).exec().then((data) => {
res.json(data)
})
})
router.get('/messages', (req, res) => {
Message.find({}, (err, messages) => {
res.send(messages);
})
})
router.post('/messages', async (req, res) => {
const {booking, user, message} = req.body
try {
var msg = new Message({
booking: booking,
message: message,
user: user
});
var savedMessage = await msg.save()
console.log('saved');
var censored = await Message.findOne({
message: 'badword'
});
if (censored)
await Message.remove({
_id: censored.id
})
else
io.emit('message', req.body);
res.sendStatus(200);
} catch (error) {
res.sendStatus(500);
return console.log('error', error);
} finally {
console.log('Message Posted')
}
})
HTML
<!DOCTYPE html>
<html lang="en">
<%- include("../header.ejs") %>
<head>
<link href="/css/sb-admin-2.min.css" rel="stylesheet">
<link href="/css/chat.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"
integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous">
</script>
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
</head>
<!-- start here! -->
<section class="msger" style="margin: auto;">
<header class="msger-header">
<div class="msger-header-title">
<i class="fas fa-comment-alt"></i> Chat
</div>
<div class="msger-header-options">
<span><i class="fas fa-cog"></i></span>
</div>
</header>
<main class="msger-chat">
</main>
<form class="msger-inputarea">
<input type="hidden" name="booking" value="<%= booking %>">
<input type="hidden" id="name" class="form-control" readonly placeholder="Name"
value="<%= user.username %>">
<input type="text" name="user" value="<%= user._id %>">
<input id="message" type="text" class="msger-input" placeholder="Enter your message...">
<button id="send" type="submit" class="msger-send-btn">Send</button>
</form>
</section>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
</div>
<!-- End of Main Content -->
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="/vendor/datatables/jquery.dataTables.min.js"></script>
<script src="/vendor/datatables/dataTables.bootstrap4.min.js"></script>
<!-- Page level custom scripts -->
<script src="/js/demo/datatables-demo.js"></script>
<script type="text/javascript" src="/js/mdb.min.js"></script>
<!-- Custom scripts -->
<script>
var socket = io();
$(() => {
$("#send").click(() => {
sendMessage({
booking: $("input[name=booking]").val(),
user: $("input[name=user]").val(),
message: $("#message").val()
});
})
getMessages()
})
socket.on('message', addMessages)
socket.on('message', getMessages)
socket.emit('message', getMessages)
socket.emit('message', addMessages)
function addMessages(message) {
if(message.user && message.user != '') {
if($("input[name=user]").val() == message.user._id) {
html = '<div class="msg right-msg"><div class="msg-img" style="background-image: url('+message.user.image +')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.user.username + '</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
}
else {
html = '<div class="msg left-msg"><div class="msg-img" style="background-image: url('+message.pro.image +')"></div>'
html += '<div class="msg-bubble"><div class="msg-info"><div class="msg-info-name">' + message.pro.username + '</div><div class="msg-info-time">' + message.createdAt + '</div></div>'
}
html += '<div class="msg-text">' + message.message + '</div></div></div>'
$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://localhost:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://localhost:3000/messages', message)
}
</script>
i tried to automatically get the message without reload the page but it doenst work. Can anyone see where the problem is?
From what I know, the default behavior when you click a button with type submit inside a form, it tries to reload the page even though you haven't defined any function or other page for it to go.
You would have to get the submit event from the form and use the preventDefault() funciton for this event, check out this thread for more info:
JavaScript code to stop form submission
So you would stop the form submission and then get new messages for the page, executing the javascript to add the new messages to the page by manipulating the DOM.
You can write socker.write() method for accessing real time messages in nodejs.

Node.js server hanging on startup | Websocket connection failed

So I'm trying to host a web app using node.js express and my server.js seems to hang upon using npm start. In my package.json file it calls node server.js and everything starts properly but my website won't deploy to the local host for me to view. I have a feeling it is either something to do with the location of my css/index.html or it could be something with the way i create the request from the client side from index.html I'm new to backend, so really out in the deep on this one.
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = '/public/index.html';
const express = require('express')
var server = express();
console.log(__dirname)
server.use(express.static(__dirname + "/public"));
server.get('public/index.html', function(req, res, next) {
res.sendFile(__dirname + INDEX);
});
server.listen(PORT);
//2.) Create a websocket server
const { Server } = require('ws');
const wss = new Server({ server });
//3.) Handle connections
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('close', () => console.log('Client disconnected'));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach((client) => {
client.send(new Date().toTimeString());
});
}, 1000);
console.log('Server started at http://localhost:' + PORT);
This is my index.html below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>
UPDATE:
So the issue that seems to be popping up now is
WebSocket connection to 'ws://localhost:2525/' failed
var ws = new WebSocket(HOST);
So the error is happening between the handshake between the client and server
The server.js
//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = "/public/index.html";
const express = require("express");
const { createServer } = require("http");
const app = express();
const httpServer = createServer(app);
// Static files
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res, next) {
res.sendFile(__dirname + INDEX);
});
//2.) Create a websocket server
const { Server } = require("ws");
const wss = new Server({ server: httpServer });
//3.) Handle connections
wss.on("connection", ws => {
console.log("Client connected");
ws.on("close", () => console.log("Client disconnected"));
});
//4.) Boradcast updates
setInterval(() => {
wss.clients.forEach(client => {
client.send(new Date().toTimeString());
});
}, 1000);
httpServer.listen(PORT, () => console.log("Server started at http://localhost:" + PORT));
The index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>am i sheep</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<div>
<span>
<h3> Am I Sheep<h3>
</span>
</div>
<div>
</div>
<div>
<input type="file" id="fileID" hidden></input>
<label for='fileID'>select image</label>
</div>
<div>
<h1 id='server-time'>current time</h1>
<script>
var HOST = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(HOST);
var el;
ws.onopen = function () {
alert('Connection Open');
};
ws.onerror = function (error) {
alert('Error');
};
ws.onmessage = function (event) {
el = document.getElementById('server-time');
el.innerHTML = 'Server time: ' + event.data;
};
</script>
</div>
</body>
</html>

Express - Cannot POST /quotes

Note I did shuffle through a LOT of answers, couldn't find one that matched mine.
Trying to learn express and node. When submitting the form in index.html, the following returns "Cannot POST /quotes" in browser and nothing in the console, but the GET method works fine and loads the page.
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening to port 3000");
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post('/post', (req, res) => {
console.log("Hellloooooooooo!");
});
index
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<form action="/quotes" method="POST">
<input type="text" placeholder="name" name="name">
<input type="text" placeholder="quote" name="quote">
<button type="submit">SUBMIT</button>
</form>
</body>
</html>
there is no quotes route, you have only 2 routes and only one post /post route but no post /quotes route
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening to port 3000");
});
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post('/post', (req, res) => {
console.log("Hellloooooooooo!");
});
// just make a simple quotes route
app.post('/quotes', (req, res) => {
console.log("hello from quotes route!");
});

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>

Track click event through socket.io

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>

Resources