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>
Related
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>
here is my app.js
const express = require('express');
const upload = require("express-fileupload");
const app = express();
app.use(upload());
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res){
if(req.files){
console.log(req.files);
}else{
console.log("error");
}
})
app.listen(3000, function(){
console.log("Success");
})
and here's the index.html
<!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>Document</title>
</head>
<body>
<h1>File upload in node js</h1>
<form action="/" method="POST">
<input type="file" name="file">
<button type="submit" value="upload">upload</button>
</form>
</body>
</html>
i get "error" from the console which means req.files is empty or does not exist i guess
i don't know how to fix this, i've started using fileupload today so i'm not that familiar to that
Help please
when submitting a file, you must use the multipart / formdata tag. see
<form action="/" method="POST" enctype='multipart/form-data'>
<input type="file" name="file">
<button type="submit" value="upload">upload</button>
</form>
also, when making a post request with javascript, you must send it as new FormData (). see
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
When a user clicks an html button (#new) I want to store their socket.id into an array (userQueue) on my node server but I'm having trouble figuring out how to do this. Do I need to set up a post request or is there a way through socket.io?
App.js (Server):
// App setup
var express = require('express'),
socket = require('socket.io'),
app = express(),
bodyParser = require("body-parser");
var server = app.listen(3000, function() {
console.log('listening to requests on port 3000');
});
var io = socket(server);
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
// Room Logic
var userQueue = [];
io.on('connection', function(socket) {
console.log('made socket connection', socket.id);
socket.on('chat', function(data) {
io.sockets.emit('chat', data);
});
socket.on('typing', function(data) {
socket.broadcast.emit('typing', data);
});
});
Chat.js (client side):
// Make connection
var socket = io.connect('http://localhost:3000');
// Query DOM
var message = document.getElementById('message');
handle = document.getElementById('handle'),
btn = document.getElementById('send'),
btnNew = document.getElementById('new'),
output = document.getElementById('output'),
feedback = document.getElementById('feedback');
// Emit events
btn.addEventListener('click', function(){
socket.emit('chat', {
message: message.value,
handle: handle.value
});
});
message.addEventListener('keypress', function() {
socket.emit('typing', handle.value);
});
// Listen for events
socket.on('chat', function(data) {
feedback.innerHTML = ""
output.innerHTML += '<p><strong>' + data.handle + ':</strong>' + data.message + '</p>'
});
// Emit 'is typing'
socket.on('typing', function(data) {
feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>'
});
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>WebSockets 101</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/styles.css">
</head>
<body>
<div id="mario chat">
<div id="chat-window">
<div id="output"></div>
<div id="feedback"></div>
</div>
<input id="handle" type="text" placeholder="Handle">
<input id="message" type="text" placeholder="Message">
<button id="send">Send</button>
<button id="new">New</button>
</div>
<script type="text/javascript" src="/chat.js"></script>
</body>
</html>
I believe that a post request will probably work as well, but if you want to simply work with socket.io you can consider doing something similar to your chat event by adding this in your chat.js:
btnNew.addEventListener('click', function() {
socket.emit('new user', socket.id);
});
And on the server side, app.js:
socket.on('new user', function(id) {
userQueue.push(id);
});
And it should be stored in the array. Hope this helps!
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>