Chat app. using express and socket.io - node.js

I have a group chat app. When client login with his email and password, he would be directed to chat page with his name on top and he would able to chat with online user.How can my app. identify from which user message was sent. One possibility is to send socket.id along with message to server for identifying user but socket.id get changed on refreshing the page.
login.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/loginstyle.css" />
</head>
<body>
<form class="css" method="post" action="http://192.168.1.3:9373/valid" >
<fieldset >
<input type="text" name="email" class="inputemail" placeholder="Email" />
</fieldset>
<fieldset >
<input type="password" name="pass" class="inputpassword" placeholder="Password" />
</fieldset >
<fieldset >
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect('http://192.168.1.3:9373');
</script>
</body>
</html>
chat.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="name"> Welcome </div>
<br></br>
<div class="chat"></div>
<form>
<input type="text" class="msg"> </input>
<button type="submit" class="enter">Send</button>
<input type="file" class="file"></input>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
var socket = io.connect('http://192.168.1.3:9373');
var online=[];
var checkFile=0;
$.get("/getName", function(string){
username=string;
$('.name').append(username);
});
$('.enter').bind("click",function(){
$.get("/getMsg", function(){
setTimeout (function(){
socket.emit('chat message',$('.msg').val() );
$('.msg').val('');
},0);
});
return false;
});
socket.on('chatmessage', function(name,msg){
var block= $("<div class='message'> </div>");
if(msg.length){
var messenger= $("<div class='messenger'> </div>");
messenger.append(name);
block.append(messenger);
var text;
text=$("<div class='text'></div>");
text.append(msg);
block.append(text);
block.append($("<div class='pad'></div>"));
$('.chat').append(block);
}
});
});
</script>
</body>
</html>
server.js
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, Twit = require('twit')
, io = require('socket.io').listen(server)
, os = require('os')
, open = require('open')
, bodyParser = require('body-parser')
, connect = require('connect')
, cookieParser = require('cookie-parser')
, session = require('express-session')
, sessionStore = session.MemoryStore()
, async = require('async')
, mysql = require("mysql");
var id=[];
var a;
server.listen(9373,'192.168.1.3');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("secret"));
app.use(session({
store: sessionStore,
secret: "54321",
saveUninitialized: true,
resave: true
}));
app.get('/loginme', function (req, res) {
res.sendfile(__dirname + '/loginmysql.html');
});
app.get('/option', function (req, res) {
res.sendfile(__dirname + '/option.html');
});
app.get('/getName', function (req, res) {
var r = {};
r.name = req.session.userid;
res.send(r.name);
});
app.get('/getMsg', function (req, res) {
a = req.session.id;
res.json(a);
});
app.get('/chat', function (req, res) {
res.sendfile(__dirname + '/chat.html');
});
app.post('/valid', function (req, res) {
var username=req.body.email;
var password=req.body.pass;
var connection = mysql.createConnection({
"hostname": "localhost",
"user": "root",
"password": "vk123",
"database": "login"
});
connection.connect();
connection.query('SELECT * FROM id WHERE email=? AND password=?', [username,password], function(err, rows){
if (err){
throw err;
}else{
var name=rows[0].name;
req.session.userid = name;
id.push({sid:req.session.id, username:req.session.userid});
res.redirect('http://192.168.1.3:9373/option');
io.sockets.on('connection', function (socket){
io.emit('name',name);
});
}
});
connection.end();
});
io.sockets.on('connection', function (socket){
socket.on('chat message', function(msg){
var user;
var i;
for(i=id.length-1; i>=0; i--){
if(id[i].sid == a){
user=id[i].username;
break;
}
}
io.emit('chatmessage',id[i].username,msg);
});
});
app.use(express.static(__dirname+'/public'));

Related

Socket.io does not get the message automatically

i tried to emplement socket.io but it does not show the way that it should be. Can anyone know where the problem. i tried to solve this around 2 weeks. Its headache to me. I tried many time already which is used emit,write, all of it. this is my code
HTML
<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" id="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>
<script type="text/javascript" src="/js/mdb.min.js"></script>
<script src="/socket.io/socket.io.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)
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>'
window.scrollTo(0, document.body.scrollHeight);
$("#msger-chat")+$(".msger-chat").append(html)
}
function getMessages() {
$.get('http://127.0.0.1:3000/messageslist/<%=booking%>', (data) => {
data.forEach(addMessages);
})
}
function sendMessage(message) {
$.post('http://127.0.0.1:3000/messages', message)
}
</script>
this is my routes
Route
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.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')
}
})
Server
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')
})
var server = http.listen(3000, () => {
console.log('Server is started on http://127.0.0.1:'+ server.address().port);
});
Im expecting someone can go thru my codes and solve the problem. i thinks my problem at html socken.on. but im not sure enough.

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.

Getting undefined from req.body in express using body-parser

iv'e read and tried all solutions in all topics, i'm a begginer with 3 month of Experince in web devolepment. usually i program with python.
So i'm sorry for any begginer mistakes.
I'm trying to set up a register form.
I'm trying to send the register data to the console with console.log.
In other page of the website involving file upload i did it succsesfully using multer.
I dont know why , but when using body-parser im allways getting undifined . No matter what!
can you see any problems in the html or express.js code ?
(english is not my native language , sorry for any spelling mistakes.)
(the wierd charchter's are Hebrew)
HTML CODE ->
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<meta charset="utf-8">
<title>Register Page.</title>
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Heebo:wght#300&display=swap" rel="stylesheet">
<link rel="icon" href="favicon.ico?v=2">
</head>
<body>
<div class="register_div">
<h1 class="registerH1">טופס הרשמה למערכת</h1>
<img src="pngegg.png" alt="angle_photo" class="angleImg">
<form class="registerForm" action="/" method="post" >
<label for="Fname">שם פרטי:</label>
<br>
<input type="text" name="register_Fname" class="inputTextRegister" required id="register_Fname">
<br>
<label for="Lname">שם משפחה:</label>
<br>
<input type="text" name="register_Lname" class="inputTextRegister" required id="register_Lname">
<br>
<label for="email"> כתובת מייל: </label>
<br>
<input type="email" name="register_email" class="inputTextRegister" required id="register_email">
<br>
<label for="levelpass">סיסמת הדרגה:</label>
<br>
<input type="text" name="masonLevelpass" required id="masonLevelpass" class="inputTextRegister">
<br>
<label for="pass">סיסמה:</label>
<br>
<input type="password" name="register_password" value="********" class="inputTextRegister" required id="register_password">
הצג סיסמה:<input type="checkbox" onclick="showPassFunc()">
<br>
<br>
<button type="submit" name="submitbutton">הרשמה</button>
<div class="toRegister"><a class="second" href="login">התחברות</a></div>
</form>
</div>
<script>function showPassFunc() {
var x = document.getElementById("pass");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}</script>
</body>
</html>
epxress code ->
const express = require('express');
const request = require("request")
const ejs = require("ejs")
var path = require('path');
var favicon = require('serve-favicon');
const app = express();
const port = 8080;
const session = require('express-session');
var mysql = require('mysql');
const bodyParser = require('body-parser');
const https = require("https");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// connect to the database
require("dotenv").config()
const DB_HOST = process.env.DB_HOST
const DB_USER = process.env.DB_USER
const DB_PASSWORD = process.env.DB_PASSWORD
const DB_DATABASE = process.env.DB_DATABASE
const DB_PORT = process.env.DB_PORT
const db = mysql.createPool({
connectionLimit: 100,
host: DB_HOST,
user: DB_USER,
password: DB_PASSWORD,
database: DB_DATABASE,
port: DB_PORT
})
//CONNECT TO USERS TABLE FREEMASONS DATABASE
const bcrypt = require("bcrypt")
//CREATE USER
app.post('/', async(req, res, next) =>{
var fname = req.body.register_Fname;
var lname = req.body.register_Lname;
var email = req.body.register_email;
var levelpass = req.body.masonLevelpass;
var pass = req.body.register_password;
console.log(fname,lname,email,levelpass,pass)
})
//Static files
app.use(favicon(path.join(__dirname, '/public', 'favicon.ico')));
app.use(express.static('public'));
//EMD OF STATIC FILES
// Set views
app.set('views', './views')
app.set('view engine', 'ejs')
app.get('', (req, res) => {
res.render('index')
});
app.get('/upload_files', (req, res) => {
res.render('upload_files')
});
app.get('/my_account', (req, res) => {
res.render('my_account')
});
app.get('/login', (req, res) =>{
res.render('login')
});
app.get('/register', (req, res) =>{
res.render('register')
});
app.listen(port, function(){
console.log("server is started on port " + port);
});
// END OF VIEWS
Thank you !

How to use sweetalert in nodejs?

I have a nodejs code given with html code, I want to show a sweet alert on client side,after process a function in nodejs?.
var express = require('express');
var router = express.Router();
const Swal = require('sweetalert2');
router.post('/add', function(req, res, next) {
Swal('Hello world!');
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form action="/add" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
Here's the only way you can show a popup swal
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.json("Hello world!")
});
<!DOCTYPE html>
<html lang="pt_br">
<head>
</head>
<body>
<h1 class="text-center title-1"> Cad </h1>
<form id="form" action="#" method="post">
<input type="submit" value="Save"/>
</form>
</body>
</html>
<script>
//import JQuery from script
//import swal script
$("#form").on("submit", function(e){
e.preventDefault();
$.ajax({
url: "/add",
method: "post"
}).done(d=>{
swal(e.responseJSON);
});
})
</script>
Here you can do using EJS
var express = require('express');
var router = express.Router();
router.post('/add', function(req, res, next) {
res.status(201).render('new', { isAdded : true } );
});
In HTML side
<% if (isAdded) { %>
<script>
Swal.fire(
'Good job!',
'Data saved',
'success'
)
</script>
<% } %>
In order to deal with this, you can use query parameters.
So, Here is what you can do
On the server
var express = require('express');
var router = express.Router();
router.post('/login', (req, res)=>{
res.redirect("/login?success=true&message=Logged In Successfully")
});
On the Client-Side (EJS)
<script>
var urlParams = new URLSearchParams(window.location.search);
if(urlParams.has('success') && urlParams.get('success')){
swal({
title: "Failed",
text: `${message}`,
icon: "error",
button: "Okay",
}).then(()=>{
console.log(window.location.hostname)
window.location.replace(window.location.origin + '/login');
})
}
This will simply popup swal. And you can toggle the value of success to render error and success messages.

Rethinkdb node change feed to HTML

I am trying to display any change feed from my rethinkdb database to the HTML (front-end) but I am not able to display any change feed.
Can you please help me how to solve this issue?
The file is app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
users = {},
db='testing',
table = 'todos';
io = require('socket.io').listen(server);
var bodyParser = require('body-parser');
server.listen(5000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var config = require(__dirname + '/config.js');
var r = require('rethinkdbdash')(config.rethinkdb);
io.sockets.on('connection', function(socket){
r.db(db).table(table).pluck('title').changes().run().
then(function(feed){
feed.each(function(err, item){
console.log(JSON.stringify(item, null, 2));
io.emit('new message', item);
});
});
});
the config.js file
module.exports = {
rethinkdb: {
host: '192.168.2.3',
port: 28015,
authKey: '',
db: 'testing'
},
express: {
port: 5000
}
};
the index.html file
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat{
height:500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data){
$chat.append(data + "<br/>");
});
</script>
</body>
</html>
you have some syntax error on index.html which prevents client side running, then the main issue is you pluck on wrong field.
Here is the code that works:
app.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
users = {},
db='testing',
table = 'todos';
io = require('socket.io').listen(server);
var bodyParser = require('body-parser');
server.listen(5000);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var config = require(__dirname + '/config.js');
var r = require('rethinkdbdash')(config.rethinkdb);
io.sockets.on('connection', function(socket){
r.db(db).table(table)
.pluck('title')
.changes()
.run()
.then(function(feed){
feed.each(function(err, item){
console.log(JSON.stringify(item, null, 2));
io.emit('new message', item.new_val.title);
})
})
})
index.html
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat{
height:500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function(data){
$chat.append(data + "<br/>");
});
})
</script>
</body>
</html>
Notice that, on a change feed, you get back documents like this:
{
"new_val": {
"id": "862e6410-f686-4a70-8a52-d4387181d4f2",
"title": "12"
},
"old_val": null
}
If you return the whole document, then the string concat on client $chat.append(data + "<br/>") may get an error or a string of 'object Object' because data is a object, not a string.
If you returns only title like this:
io.emit('new message', item.new_val.title);
Then the string concat will run ok.
Also, your code is very messy. I suggest you get some basic foundation of JavaScript in generally.

Resources