socket console.log() not showing when connected - node.js

I'm completely new to socket.io and I'm trying to connect a client to the server.
This is app.js.
const socketio = require("socket.io");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.get("/", (req, res) => {
res.render("index");
});
const server = app.listen(process.env.PORT || 3000, () => {
console.log("server is running...");
});
// Initialize socket for the server
const io = socketio(server);
io.on("connection", socket => {
console.log("New user connected");
});
This is index.ejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Real time Chat App</title>
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
/>
</head>
<body>
<div class="container">
<div class="title">
<h3>Realtime Chat Room</h3>
</div>
<div class="card">
<div class="card-header">Anonymous</div>
<div class="card-body">
<div class="input-group">
<input
type="text"
class="form-control"
id="username"
placeholder="Change your username"
/>
<div class="input-group-append">
<button class="btn btn-warning" type="button" id="usernameBtn">
Change
</button>
</div>
</div>
</div>
<div class="message-box">
<ul class="list-group list-group-flush" id="message-list"></ul>
<div class="info"></div>
</div>
<div class="card-footer">
<div class="input-group">
<input
type="text"
class="form-control"
id="message"
placeholder="Send new message"
/>
<div class="input-group-append">
<button class="btn btn-success" type="button" id="messageBtn">
Send
</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
<script src="/js/chatroom.js"></script>
</body>
</html>
This is chatroom.js.
(function connect() {
let socket = io.connect("http://localhost:3000")
})();
The problem is I don't know why io.on("connection", socket => { console.log("New user connected"); }); not working here. Everything seems to be OK in Google Chrome console, but the message doesn't appear in VS code terminal when I go to localhost website. The terminal always looks like this when I refresh the page.
vs code terminal
Is there anything wrong with my code?

I solved it already. I change <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script> to <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js"></script> and still have no idea what the problem is ,but it works.

I think it's a cors origin problem, use Firefox to see it in the console
And that't how you can resolve it : socket.io, 'Access-Control-Allow-Origin' error

Related

How do i get my mongodb dataset to display in an ejs file

Rebuilding a previous project and trying to learn node and CRUD functions with mongodb. i have a connection to my database and a separate server.js file with mongoose and express.
in server.js the server runs correctly im just not sure how to view my data on the page
here is my code:
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const ejs = require('ejs');
app.set('view engine', 'ejs');
mongoose.connect("mongodb connection string here");
const recipeSchema = {
title: String,
ingredients: Array,
instructions: String,
picture_link: String
}
const Recipe = mongoose.model('Recipe', recipeSchema);
app.use(express.static('public'));
app.get('/', function(req, res) {
res.render('index', {});
});
app.get('viewrecipes', function(req, res){
Recipe.find({}, function(err, recipes) {
res.render('viewrecipes', {
recipesList: recipes
})
})
});
app.listen(4000, function() {
console.log('server is running');
});
viewrecipes.ejs file
<!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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css" type="text/css">
<title>Document</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light ">
<div class="container-fluid">
<a class="navbar-brand" href="/">Recipe Fix!</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav ">
<li class="nav-item">
<a class="nav-link" id="submit-recipe" href="#">Submit a Recipe</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/viewrecipes">View Recipes</a>
</li>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search for recipes" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</ul>
</div>
</div>
</nav>
<%recipesList.forEach(recipe => {%>
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title"><%= recipe.title %></h5>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><%= recipe.ingredients %></li>
</ul>
<div class="card-body">
<%= recipe.instructions %>
</div>
</div>
<%})%>
<script src="core.js"></script>
<script src="server.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>

TypeError: Cannot read property of 'db' undefined

I am new coder and developing To-Do App. I want to connect my app to mongoDB Atlas database from VSC editor Terminal. I use Node.js (Express) and mongoDB Atlas. When I uninstall Node.js and start code from scratch, it works fine because code is all OK but next day when I get back to the same project and run it, it doesn`t work anymore. It shows up an error. You may check this terrible error here on this link: https://prnt.sc/u8paeg
let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db
let connectionString ='mongodb+srv://akhtarayaz:SpreadLoveEverywhere#cluster0.yfwfa.mongodb.net/Users?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client){
db = client.db()
app.listen(3000)
if (err) {
throw err;
}
})
app.use(express.urlencoded({extended: false}))
app.get('/', function(req, res){
db.collection('accounts').find().toArray(function(err, accounts){
res.send(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple To-Do App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1 class="display-4 text-center py-1">To-Do App</h1>
<div class="jumbotron p-3 shadow-sm">
<form action="/create-account" method="POST">
<div class="d-flex align-items-center">
<input name="account" autofocus autocomplete="off" class="form-control mr-3" type="text" style="flex: 1;">
<button class="btn btn-primary">Add New Item</button>
</div>
</form>
</div>
<ul class="list-group pb-5">
${accounts.map(function(account){
return `<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between">
<span class="item-text">${account.text}</span>
<div>
<button class="edit-me btn btn-secondary btn-sm mr-1">Edit</button>
<button class="delete-me btn btn-danger btn-sm">Delete</button>
</div>
</li>`
}).join('')}
</ul>
</div>
</body>
</html>
`)
})
})
app.post('/create-account', function(req, res){
db.collection('accounts').insertOne({text: req.body.account}, function(){
res.redirect('/')
})
})

Node.js (express framework): Post method not working

I am able to run the Get method and HTML form also visible on browser using Get method but when I am clicking on submit button nothing is happening, no error nothing. it shows the same HTML form page.
HTML code:
<!DOCTYPE html>enter code here
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form action="/" method="post">
<h1>Calculator</h1>
<input type="text" name="num1" placeholder="Number 1">
<input type="text" name="num2" placeholder="Number 2">
<button action="/" type="button" name="button">Submit</button>
</form>
</body>
</html>
Node Js code:
//jshint esversion:6
const express=require("express");
const app=express();
app.get("/", function(req,res){
res.sendFile( __dirname+"/index.html");
});
app.post("/", function(req,res){
res.send("Thanks for post");
});
app.listen(3000, function(){
console.log("Server Started On Port 3000");
});
Your button type should be Submit
<button type="submit" value="Submit">Calculator</button>

connects to server but database is not created and not saving chat history. i am using nodejs, mongodb to save and robomongo to view

i developed a client side application and have two html files
This is index.html and after filling form redirect to chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Join | chatApp</title>
<meta name = "viewport" content ="width=deveice-width, initial-scale=1, user-scalable =no ">
<link rel="stylesheet" href="/css/style.css">
</head>
<body class ="centered-form">
<div class ="centered-form__form">
<form action="/chat.html">
<div class="form-field">
<h3>want to Join a Chat</h3>
</div>
<div class="form-field">
<label>Name</label>
<input type="text" name="name" autofocus/>
</div>
<div class="form-field">
<label>Room Name</label>
<input type="text" name="room"/>
</div>
<div class="form-field"></div>
<button>Join</button>
</form>
</div>
</body>
</html>
This is the chat.html and wants to save all the chat history in a database.
<body class="chat">
<div class="chat__sidebar">
<h3>people</h3>
<div id="users">
</div>
</div>
<div class="chat__main">
<ol id="messages" class="chat__messages"></ol>
<div class="chat__footer">
<form id="message-form" method ="post" action="/add">
<input type="text" name="message" placeholder="message" autofocus autocomplete ="off"/>
<button>send</button>
</form>
<button id="send-location">send location</button>
</div>
</div>
<script id="message-template" type="text/template">
<li class="message">
<div class="message__title">
<h4>{{from}}</h4>
<span>{{createdAt}}</span>
</div>
<div class="message__body">
<p>{{text}}</p>
</div>
</li>
</script>
<script id="location-message-template" type="text/template">
<li class="message">
<div class="message__title">
<h4>{{from}}</h4>
<span>{{createdAt}}</span>
</div>
<div class="message__body">
<p> My current location </p>
</div>
</li>
</script>
</body>
code to save in a database
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var mongoose =require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/chatApp');
var nameSchema = new mongoose.Schema({
message:{type: String}
});
var User = mongoose.model("User", nameSchema);
app.get('/', (req, res)=>{
res.sendFile(__dirname, '/public/chat.html');
});
app.post('/add', function (req, res){
var message = req.body.message;
var myData = new User();
myData.message = message;
myData.save().then((item)=>{
res.send('item saved');
},(err)=>{
res.status(400).send('unable to save');
});
});

No data send with socket.io

I have to send data using socket.io.when a user enter his login and a password,he will be redirect to index.ejs and the username will be send to the server.
route.js (I mentioned only the part of the script not the hole script to show that when the login and password are correct a user get an index page and the userobject send to the index):
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/signin');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('index', {title: 'Home', user: user});
}
};
app.js:
io.sockets.on('connection', function (socket) {
socket.on("new_user",function(user1){
console.log("a new user is connected",user1);
var current_date=new Date();
var date=current_date.toString();
ex.user_connect(user1,date);
});
});
index.ejs:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width ,initial-scale=1.0" />
<title><%= title %></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style/style.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">HomePage</a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><%= user.username%></li>
<li><span class="glyphicon glyphicon-log-out"></span> Sign out</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-sm-6">
<div class="container">
<h2>Led1</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-default btn-lg" id="led1" align="center">check it</button>
<!-- Modal -->
<div class="modal fade" id="model_led1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal" id="close">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Settings</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form">
<img src="style/images/led.png" id="led" class="img-responsive"/>
<button type="button" class="btn btn-success btn-block" id="led1_activ"><span class="glyphicon glyphicon-off"></span> Activate</button>
<button type="button" class="btn btn-success btn-block" id="led1_desactiv"><span class="glyphicon glyphicon-off"></span> Desactivate</button>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal" id="cancel_button"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
var user1 = user.username;
socket.emit('new_user',user1);
</script>
NB:I got the username on the navbar but I don't get it on the server console.
Ejs render all template variables in server and then return plain html to the client , so
Inside your script , do you have variable global user initialized? :
var user1 = user.username // var user = {username:"foo":} ,something like that before.
If you trying to get user from template variable you could try:
var user1= "<%= user.username%>";
This will render <%= user.username%> inside script tag before send to the client ( browser)

Resources