I am building a real-time chat application using Node.js and socket.io.
I have built two js files - index.js for handling socket connection server requests and client.js for the client-side code. When I include console.log, I cannot get the output in the command line.
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">
<!--connects server and client-->
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script src="./js/client.js"></script>
<link rel="stylesheet" href="./css/style.css">
<title>NiChat App</title>
</head>
<body>
<!--Navbar-->
<nav>
<img class="logo" src="logo.png" alt="Log">
</nav>
<!--Container for the chat app-->
<div class="container">
<div class="message" id="m-left">Palpatine: Did you ever hear the tragedy of Darth Plagueis the wise?</div>
<div class="message" id="m-right">Anakin: No.</div>
</div>
<!--Send box-->
<div class="send">
<form id="send-container" action="#">
<input type="text" name="msgInp" id="msgInp">
<button class="btn" type="submit">Send</button>
</form>
</div>
</body>
</html>
index.js
//file which will host the socket io
const io = require("socket.io")(8000)
const users = {};
io.on('connection', (socket) => { //io.on listens to several socket connections
console.log('a user connected');
socket.on('new-user-joined', Name => { //accepts an event 'new-user-joined'
console.log('New user', Name)
users[socket.id] = Name;
socket.broadcast.emit('user-joined', Name)
});
socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, name: users[socket.id] })
});
})
client.js
const socket = io('http://localhost:8000');
const form = document.getElementById('send-container');const msgInp = document.getElementById('msgInp');const msgContainer = document.querySelector(".container")const Name = prompt("Enter your name to join");socket.emit('new-user-joined', Name)
The client.js file is within the js folder.
The index.js is within the node_modules folder.
Please help me out.
I tried putting console.log at different places of both the js files but am unable to produce an output.
This answer provided the solution to my question.
Here is the link
Adding this { transports: ['websocket'] } inside the io makes the problem go away.
Related
i want a user to input data in a form i created and i want the data to be sent to mongodb atlas.
so i host the form locally and it gives me an error "require is not defined".
my question is do i have to bundle the mongodb module or is there a way to do it without bundleing.
this is the code.
I USE THE VSCODE LIVE EXTENSION TO HOST.
document.querySelector(`input[type="submit"]`).onclick = () =>
{
var x = document.forms["form1"]["username"].value;
var password = document.forms["form1"]["password"].value;
var email ={
name : `${x}`,
password : `${password}`
};
if(document.querySelector(`input[type="checkbox"]`).checked){
var json = JSON.stringify(email);
var MC = require('mongodb').MongoClient;
var url = "mongodb+srv://<username>:<password>#cluster0.xjoqb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
MC.connect(url, (err, db) => {
if (err) {
throw err;
}
console.log(`Connected`);
var data = db.db(`mydb`);
data.createCollection(`first`, (err, res) => {
if (err) throw err;
console.log(`collection created`)
});
data.collection(`first`).insertOne(email, (err, res) => {
if(err) throw err;
console.log(`inserted`);
db.close();
});
});
}
}
This is the 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">
<meta name="google-signin-client_id" content="707054985283-cirkm54740d0pm838hrgq7etkp3hu3ej.apps.googleusercontent.com">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<fieldset>
<h1 id="greeting">Welcome Back</h1>
<p id="greeting2">Let's Get Signed In</p>
<form name="form1" class="form" method="POST" autocomplete="off" spellcheck="false">
<div class="g-signin2" data-onsuccess="onSignIn"></div>
<div class="con1">
<input type="text" id="name" name="username" placeholder="Enter Your Email Address">
<img src="https://img.icons8.com/windows/50/000000/name.png" class="nameicon">
</div>
<div class="con2">
<input type="password" id="pass" name="password" placeholder="Enter Your Password">
<img src="https://img.icons8.com/windows/50/000000/password.png" class="passicon">
</div>
</form>
Forgot Password?
<div id="alm">
<input type="checkbox" id="remember" name="remem">
<label for="remem">Remember Me</label>
</div>
<form class="button1">
<input type="submit" name="submit" id="submit1">
</form>
</fieldset>
</body>
<script src="script.js"></script>
</html>
Databases (remote or local) are server side services. You need a back end app that handles the post request from the form located in the front end part and then from the backend trigger any action into Mongo Atlas.
Going with a NodeJS & Express stack could be a good option for you (you will also need to work with mongo in the backend, but in this case you will be storing the data in a remote Mongo Database).
This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 1 year ago.
OVERVIEW
I am trying to create a Dapp with Ethereum and the course I am following (Udacity Blockchain Nanodegree Program) is asking us to create a HTML page from where a User using the page's buttons can interact with the Smart Contract. I am a beginner with HTML and anything related to hosting servers and routing, etc. So, I created two really basic functions in the Javascript file to practice how to call them and later on replace it with the correct web3 functions.
PROBLEM
The thing is that I've used a separated Javascript file for my functions and when I try to call those functions from the HTML file it doesn't work.
I've read that the main reason is that the functionFile.js is not in the server.js and it should have a route.
QUESTIONS
Why my code doesn't work? Could you explain it so that a beginner like me can understand it?
What is the code that I need to implement in server.js that will solve these errors and make the page work as intended?
PROJECT DIRECTORY STRUCTURE
SERVER.JS CODE
const http = require('http');
const fs = require('fs');
const PORT = 8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function (request, response) {
response.writeHeader(200, { "Content-Type": "text/html" });
response.write(html);
response.end();
}).listen(PORT);
});
TEST.JS CODE
function letMeCallYou() {
alert("Bazinga!!! you called letMeCallYou");
}
function myfunction() {
document.write("welcome to Javatpoint");
}
INDEX.HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<title>StarNotary DAPP Front End</title>
<meta name="viewport" content="width=device-width, initial-scale=1"
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
</head>
<style>
input {
display: block;
margin-bottom: 12px;
}
</style>
<body>
<h1>StarNotary DAPP</h1>
<h3 id='name'>Star Name: </h3>
<hr>
<h3 id='owner'>Star Owner: </h3>
<hr>
<h3>Claim Star</h3>
<hr>
<h3>TEST</h3>
<button id="test" onclick="letMeCallYou()">Testing External Javascript library</button>
<script src="scripts/test.js"></script>
<script>letMeCallYou();</script>
</body>
</html>
ERROR SCREENSHOT
So I managed to solve my problem after modifying the server.js file folder. Here is my updated project file architecture with the updated server.js code.
PROJECT ARCHITECTURE
SERVER.JS CODE
const express = require('express');
const app = express();
// THIS LINE WAS THE SOLUTION TO THE PROBLEM
app.use(express.static('./public'));
app.get('/', (req, res) =>{
res.setHeader('Content-type', 'text/html');
res.sendFile('./public/index.html');
});
app.listen(8080, () =>{
console.log('APPLICATION INITIALIZED....');
});
INDEX.HTML CODE
<!DOCTYPE html>
<html lang="en">
<head>
<title>StarNotary DAPP Front End</title>
<meta name="viewport" content="width=device-width, initial-scale=1"
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
</head>
<style>
input {
display: block;
margin-bottom: 12px;
}
</style>
<body>
<h1>StarNotary DAPP</h1>
<h3 id='name'>Star Name: </h3>
<hr>
<h3 id='owner'>Star Owner: </h3>
<hr>
<h3>Claim Star</h3>
<hr>
<h3>TEST</h3>
<button id="test" onclick="letMeCallYou()">Testing External Javascript library</button>
<script src='./scripts/app.js'></script>
</body>
</html>
EXECUTION SCREENSHOT
Ok so this is weird, I have a frontend js file and a html file :
const conn = new WebSocket('ws://localhost:8000');
const main = document.querySelector('.main');
const send = document.querySelector('#send');
const text = document.querySelector('#text');
conn.onopen = () => {
console.log('connetion open');
conn.send('heyya');
}
conn.onmessage = message => main.innerHTML += message.data;
conn.onerror = error => console.log('web socket not available');
send.addEventListener('click', e => {
console.log('send');
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script defer src="app.js"></script>
</head>
<body>
<div class="main">
<input type="text" name="" id="text">
<button id="send">Send</button>
</div>
</body>
</html>
whenever the websocket is up and running, clicking on send button does nothing and variable send doesn't seem to be referring to the send button in html.
But whenever websocket is offline send button is working as expected.
Is it some typo or any other mistake by me or something with JS ?
One thing that I noticed you need to improve is that you should:-
conn.send(JSON.stringify('heyya'))
while sending data on WebSocket.
And do the same while receiving:-
JSON.parse(message), and then use the "message" the way you want to.
conn.onmessage = message => main.innerHTML += message.data;
is equal to
main.innerHTML = main.innerHTML + message.data
Will destroy everything inside and recreate it. When this happens the event bindings are gone. You should use a method like appendChild or you can add a new element to inject new messages into, like:
<body>
<div class="main">
<input type="text" name="" id="text">
<button id="send">Send</button>
<ul id="messages"></ul>
</div>
</body>
I'm fairly new to Javascript I have been playing with some data fetching for the past few days. I created this very simple program (if you can even call it that), where if you click a button, it will generate a div with a random user (using jsonplaceholder API). My issue is, that whenever the button is clicked, it gives me all 10 users at once. I'd like it to give me one user with each click instead. As I said, I am fairly new to JS so I'm not sure how to aproach this (I guess some sort of a loop would be involved?). Any sort of advice, tips or anything would be welcomed ! Thank you !
Here is my code (Using Bootstrap 4 for styling and Axios for data fetching):
const mainButton = document.getElementById('mainButton');
const targetDiv = document.getElementById("targetDiv");
mainButton.addEventListener('click', () => {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function(response) {
let ourRequest = response;
renderData(ourRequest.data);
})
.catch(function(error) {
console.log(error);
});
function renderData(data) {
var stringHTML = "";
for (i = 0; i < data.length; i++) {
stringHTML += `
<div class="col-md-4">
<div class="card">
<div class="card-header">
User ID: #${data[i].id}
</div>
<div class="card-body">
<h4 class="card-title">${data[i].name}</h4>
<p class="card-text">Email - <em>${data[i].email}</em></p>
<p class="card-text">Phone - <em>${data[i].phone}</em></p>
<p class="card-text">Address - <em>${data[i].address.street}, ${data[i].address.city}, ${data[i].address.zipcode}</em></p>
</div>
</div>
</div>
`;
}
targetDiv.insertAdjacentHTML("beforeend", stringHTML);
}
});
<!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" href="main.css">
<title>JSON Users</title>
</head>
<body>
<div class="container">
<div class="text-center my-5">
<h1 class="display-4">Random JSON Users</h1>
<p>This is a random user generator, click the below button to get a
random person!</p>
<button id="mainButton" class="btn btn-primary">Get User!</button>
</div>
<!-- Users -->
<div id="targetDiv" class="row">
</div>
</div>
<!-- JavaScript -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
If I get it right that your GET method is asking for users, so response contains more that one user. This response you send to renderData method and there you generate your div for each user from response. I supouse to change your GET method to get only one user or send only one user to renderData method like ourRequest.data[0] from your current solution.
I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body