I'm following a tutorial about making a rock paper sissors game with a chat using socket.io and express. I'm only making the chat.
But I'm getting an error that the person in the tutorial isn't getting. I don't know how to fix it. I've search google but could only find very complicated solutions.
The error that I get when I try to send a message is 'ERR_CONNECTION_REFUSED'.
Here is my code:
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat</title>
</head>
<body>
<div id="chatWrapper">
<ul id="chatUl"></ul>
</div>
<div class="buttons">
<form id="chatForm">
<input id="chat"/>
<button id="verstuur">Verstuur</button>
</form>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>
Server.js
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const clientPath = `${__dirname}/../client`;
console.log(`Static van ${clientPath}`);
app.use(express.static(clientPath));
const server = http.createServer(app);
const io = socketio(server);
io.on('connection', (sock) => {
console.log("Iemand is verbonden");
sock.emit('message', "Hoi, je bent verbonden!");
sock.on('message', () => {
io.emit('message', text);
});
});
server.on('error', (err) => {
console.error("Server fout: " + err);
});
server.listen(8080, () => {
console.log('Chat opgestard op 8080');
});
Client.js
const writeEvent = (text) => {
// <ul> element
const parent = document.querySelector('#chatUl');
// <li> element
const el = document.createElement('li');
el.innerHTML = text;
parent.appendChild(el);
};
const onFormSubmitted = (e) => {
e.preventDefault();
const input = document.querySelector('#chat');
const text = input.value;
input.value = '';
sock.emit('message', text);
};
writeEvent('Welkom bij de chat!');
const sock = io();
sock.on('message', writeEvent);
document
.querySelector('#chatForm')
.addEventListener('submit', onFormSubmitted);
Any help?
ps. The tutorial that I am following: https://www.youtube.com/watch?reload=9&v=xVcVbCLmKew
And sorry for bad English
You just forgot the formal parameter of a function (server.js):
io.on('connection', (sock) => {
console.log("Iemand is verbonden");
sock.emit('message', "Hoi, je bent verbonden!");
sock.on('message', (/* variable here*/ text) => {
io.emit('message', text);
});
});
Also check the path to your files. Is "${__dirname}/../client" correct?
Related
i am trying to get the socket id on the client side but for some reason it's not showing. Here is my code
client side
<html>
<head>
<meta charset="utf-8" />
<title>Ringneck</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script src="https://www.WebRTC-Experiment.com/RecordRTC.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io-stream/0.9.1/socket.io-stream.js"></script>
</head>
<body>
<div style="margin: 20px">
<h1 style="font-size: 18px;">Example 7: Media Translation Streaming</h1>
<div>
<button id="start-recording" disabled>Start Streaming</button>
<button id="stop-recording" disabled>Stop Streaming</button>
</div>
<h2 style="font-size: 16px; margin-bottom: 10px;">data.textTranslationResult.translation</h2>
<p>Record your voice in English, and see the German translation.</p>
<p>Keep recording for at least 4 seconds.</p>
<textarea id="results" style="width: 800px; height: 300px;"></textarea>
</div>
<script type="text/javascript">
const startRecording = document.getElementById('start-recording');
const stopRecording = document.getElementById('stop-recording');
let recordAudio;
const socketio = io();
console.log("JS file loaded"). // sanity check to make sure file is read
const socket = socketio.on('connect', function(msg) {
console.log("JS file loaded")
console.log("socket id: ",socket.id);
});
and my server side code
const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(cors());
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/index.html'));
});
function onConnection(socket){
console.log(`Client connected [id=${socket.id}]`);
var returndata = {
"test":"yes"
}
socket.emit('server_setup', `Server connected [id=${socket.id}]`);
}
io.on('connection', onConnection);
http.listen(port, () => console.log('listening on port ' + port));
my server console log is
Client is connected [id=_RMXhb8Vz9XgSqhGAAGa]
but I could not get any response on the client side. what am i missing and how can i fix this and get the socket id ?
When I run your code, I found that there was a client-side Javascript parsing error on this line:
console.log("JS file loaded").
because of the period. When I replace that period with a semi-colon like this:
console.log("JS file loaded");
I get this output on the server:
Client connected [id=eoxspnNtoTg-2Kj3AAAB]
and this output in the debug console of the browser:
JS file loaded
socket id: eoxspnNtoTg-2Kj3AAAB
If you're not already doing so, you should be looking in the browser console for errors.
I am new to node js and js, My code is not able to cross the SQL statement
here is my app.js snippet for the SQL statement
my app.js
//declaration
const bodyParser = require("body-parser")
const fs = require('fs')
const express = require('express')
const app = express()
var session = require('express-session');
const path = require('path')
app.use("/static", express.static('./static/'));
//For the body parser
app.use(bodyParser.urlencoded({extended: false}))
//parse the application Json
app.use(bodyParser.json())
// for the MySQL page
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'login'
})
app.get ('/todo',(req,res)=>{
res.writeHead(200,{'content-type' : 'text/html'})
fs.createReadStream('project1.html').pipe(res)
})
app.listen(process.env.PORT || 3000)
my todo.js
document.addEventListener('submit',myFunction)
function myFunction(e){
console.log("in the data post method")
let sql = 'INSERT INTO `acc` (`name`) VALUES (?)'
connection.query(sql,req.body.name,(error,result)=>{
if(error) throw error
console.log('value inserted')
connection.end();
})
e.preventDefault();
var text = document.querySelector("input").value;
var text = document.querySelector("input").value;
var node = document.createElement("p");
node.id="li1"
if (text!=""){
var textnode=document.createTextNode(text);
node.appendChild(textnode); //append the value to LI
text = document.getElementById("demo")
console.log(text) ;
document.getElementById("demo").appendChild(node); //append the value to UI
document.querySelector("input").value = ""
}
// document.getElementById("demo").addEventListener('mouseover',myFunction1)
str = document.getElementById("li1")
console.log(str)
}
//SELECTING AN ELEMENT THAT WAS CREATAED DYNAMICALLY AND APPLLY SOME PROPERTY
$(document).on('click','p',function(){
$(this).css({"text-decoration": "line-through",color : "pink" });
$(this).fadeOut(1500);
// $(this).remove();
})
my project1.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>Create a table</title>
<script src="./static/todo.js"></script>
</head>
<body>
<h1>ToDo</h1>
<form id="form" action="/data" method="post">
<input type="text" name = "name" class="input" id="tt">
</form>
<div id= "lip">
<ul id="demo" id="demo">
</ul>
</div>
</body>
</html>
I want to insert the user typed value in the database as well as I have to list them in the front end, both codes work separately but when I combine them, after executing the SQL statement the browser waits for something
Please help me.
I'm currently trying to make a support application (like, to live chat with support) and I'm looking for a way to avoid the change of the socket id.
Here is my index.js code:
const app = require('express')();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on("hello",()=>{
socket.emit("hello",socket.id)
})
})
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/client/index.html")
})
server.listen(1002)
And here is my client/index.html code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<p id="socketid"></p>
<script>
const socket = io();
socket.emit("hello")
socket.on('hello',(message)=>{
document.getElementById("socketid").innerHTML=message;
})
</script>
</body>
</html>
Thanks in advance for your help!
I think you cannot make socketid constant. Every time you reconnect or connect a new socket id will be given to you. Actually why do you want to make socketid constant?
I have been trying to get the value of my text input in a form with a POST request, but on the server side, the req.body is returning a [objecet][Object] request, when indeed I put in a value. Here's my code
const express = require('express');
const path = require('path');
let app = express();
const bodyParser = require('body-parser');
//Middleware for
app.use(bodyParser.urlencoded({extended: true}))
//using a middleware to map the /assets link in the url
app.use(express.static(path.join(__dirname, '/public')));
//Setting the view engine
app.set('view engine', 'ejs');
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/index.html');
})
//Contact page
app.get('/contact', (req, res)=>{
res.sendFile(__dirname + '/contact.html');
// res.sendFile(__dirname + '/assets/appUI.js');
})
app.get('/contact-us', (req, res)=>{
res.sendFile(__dirname + '/contact.html');
})
//Handling POST request
app.post('/', (req, res )=>{
console.log('The task is '+ req.body)
})
app.listen(3000, ()=>{
console.log('The server is up and listening at port 3000!!!')
})
My index.html code is as below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" type="image/x-icon">
<title>To do app</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="animate.css">
</script>
</head>
<body onload ="appui()">
<p>CONTACT US</p>
<img src="todoImage.png" alt="" class="todoImage">
<div class="main-box">
<div class = "form-error animated shake" id = "error-message">
<p class = "form-error"><small>Please add a task</small></p>
</div>
<div class = "form-registered animated shake" id = "registered-message">
<p class = "form-registered"><small>Details added to register!</small></p>
</div>
<h1>Todo App </h1><br>
<form class="form" action="/" method="POST">
<input type="text" id="task" name = "task" value="Invents"><br>
<input type="submit" value="Add task" class="btn" name="addTask">
<input type="button" value="Clear All" class="btn clear-all" name="clearTask">
</form>
</div>
<ul class="task-list"></ul>
<script src= "appUI.js">
</script>
</body>
</html>
And my client side javascript code is as below
function appui(){
//Grabing input
const task = document.querySelector('#task');
const submit = document.querySelector('.btn');
const main = document.querySelector('.main-box');
const form = document.querySelector('.form');
const taskList = document.querySelector('.task-list');
const clearTask = document.querySelector('.clear-all')
const errorMessage = document.querySelector('#error-message');
const registeredMessage = document.querySelector('#registered-message');
//Load event listener
// loadEventlisntener()
console.log(main)
//adding submit event
submit.addEventListener('click', addTask);
//Funtion Error Display
function errorDisplay(){
errorMessage.style.setProperty('display', 'none');
}
//Funtion regsitered Display
function registeredDisplay(){
registeredMessage.style.setProperty('display', 'none');
}
//addtask
//Function addTask
function addTask(e){
if(task.value !== '') {
//create Element li
let list = document.createElement('li');
//Add a class name
list.className = 'task-value';
//create div
let div = document.createElement('div');
//Add a class name
div.className = 'main-box task animated heartBeat';
//task
let taskInput = document.createTextNode(`${task.value}`);
//append text node
div.appendChild(taskInput);
//Anchor tag
let anch = document.createElement('a');
//Add a class name
anch.className = 'deleteIcon';
//Delete mark 'X'
anch.innerHTML = `<b class="delete-icon">Delete</b>`
//Append Anchor tag to div
div.appendChild(anch);
// main.appendChild(div);
// form.parentNode.insertBefore(div, form.nextSibling);
console.log(div)
// Inserting Element after
// main.parentNode.insertBefore(div, main.nextSibling);
document.querySelector('.task-list').appendChild(div);
registeredMessage.style.setProperty('display', 'block');
setTimeout(registeredDisplay, 3000);
task.value ='';
} else{
errorMessage.style.setProperty('display', 'block');
setTimeout(errorDisplay, 3000);
}
// e.preventDefault();
}
//Deleting task
taskList.addEventListener('click', removeTask);
// Remove Task
function removeTask(e) {
if(e.target.parentElement.classList.contains('deleteIcon')) {
e.target.parentElement.parentElement.remove();
}
}
//Clear all tasks
clearTask.addEventListener('click', ()=>{
if(taskList.innerHTML === ''){
errorMessage.style.setProperty('display', 'block');
setTimeout(errorDisplay, 3000);
}else if(confirm('Are you sure ?')){
taskList.innerHTML = '';
task.value ='';
}
})
}
I'm already so frustrated, I hope you all can help out.
Thanks!
The automatic string conversion in Javascript for an object is just [Object][object] so when you do this:
console.log('The task is '+ req.body)
that's what is happening. req.body undergoes an automatic string conversion to [Object][object] and that's appended to your string.
To fix, change your code to this:
console.log('The task is ', req.body);
so that console.log() can output the whole req.body object.
Trying to use wkhtmltox to turn an HTML file to an image:
./server.js
const express = require('express');
const fs = require('fs');
const wkhtmltox = require('wkhtmltox');
const app = express();
const converter = new wkhtmltox();
app.get('/tagslegend.png', (request, response) => {
response.status(200).type('png');
converter.image(fs.createReadStream('tagslegend.html'), { format: "png" }).pipe(response);
});
var listener = app.listen(process.env.PORT, function () {
console.log('App listening on port ' + listener.address().port);
});
And ./tagslegend.html:
<!doctype html>
<html>
<body>
<dl>
<dt>中文</dt><dd>In mandarin language.</dd>
</dl>
</body>
</html>
I'm expecting back an image of the above HTML, e.g. (how my browser would render it):
Instead I get back this:
How can I render that HTML to a png dynamically with the correct chinese characters and serve it to clients?
Add
<meta charset="utf-8">
to the <head> of the HTML document