Use a Checkbox to Show Disabled Users - node.js

I'm making a website in which I show enabled users in a Bootstrap by default, but there's a checkbox to show all users. But I'm not sure how I can go about implementing it properly.
I thought about doing:
<form class="" action="/admin" method="get">
<input type="checkbox" name="showDisabled" value="">
<input type="submit" name="" value="">
</form>
And in my /admin route:
if (req.body.showDisabled) {
User.find({}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.render('pages/userTable', {users: users});
})
} else if (!req.body.showDisabled) {
User.find({enabled: true}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.render('pages/userTable', {users: users});
})
}
But that seems really janky. What's a better way to do it?

You can try this:
Router
app.get('/getDiasbleUser', function(req, res) {
var getDiasbleUser = req.params.showDisabled
if (getDiasbleUser == "Yes") {
User.find({}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.send(users);
})
} else if (getDiasbleUser == "No") {
User.find({
enabled: true
}, (err, users) => {
if (err) {
console.log(err);
}
}).then((users) => {
res.send(users);
})
}
})
HTML (Template)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form class="" action="/admin" method="get">
<input type="checkbox" id="disableId" name="showDisabled" value=""><br>
<div id="appendValue"></div>
<br>
<button class="btn btn-primary">Submit</button>
</form>
</div>
</body>
//Ajax call
<script>
$('#disableId').on('click', function () {
$(this).val(this.checked ? 1 : 0);
//console.log($(this).val());
var url = "";
if($(this).val() == 1){
url = "/getDiasbleUser?showDisabled=yes"
} else {
url = "/getDiasbleUser?showDisabled=no"
}
$.ajax({
url: url,
success: function(data){
//Here data will be return result(You will append into div or table)
//like : $('#appendValue').append(data)
}
})
});
</script>
</html>

Related

response.writeHead(302) in NodeJS not redirecting in async function callback

Below is a snippet of my NodeJS server code.
async function handleLoginReq(req, res) {
let queryDB = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(queryDB);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, {
'Location': '/experiment_page/index.html'
});
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.statusCode(302);
res.setHeader('Location', `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`)
//res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
handleLoginReq(req, res);
The client.query() function is a asynchronous function. However, none of the res.writeHead(302)'s are working inside the callback of this function. A res.writeHead(302) does work if I add it below the function call of handleLoginReq(req, res);.
handleLoginReq(req, res);
// Below redirect works
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
The above code runs when a form is submitted on /login_page/loginPage.html.
Instead of redirecting the user to either /experiment_page/index.html or back to /login_page/loginPage.html?error=something with a URL parameter, it just reloads the page to /login_page/loginPage.html.
Below is the HTML for this page.
<!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="/login_page/css/loginStyles.css">
<script src="/login_page/js/labelChange.js" defer></script>
<script src="/login_page/js/redirectSignUp.js" defer></script>
<script src="/login_page/js/loginValidation.js" defer></script>
<title>DigiChit - The Online Chit System | Login</title>
</head>
<body>
<nav class="navbar">
<ul>
<li><h1>DigiChit</h1></li>
<li>Home</li>
<li>About</li>
</ul>
</nav>
<div class="login-info">
<form method="POST" class="form">
<img src="/images/avatar.png" id="avatar" alt="avatar">
<h2>Login</h2>
<div class="input-group">
<input type="email" name="user-email" id="user-email" required>
<label for="user-email">Email</label>
<span id="email-error"></span>
</div>
<div class="input-group">
<input type="password" name="user-password" id="user-password" required>
<label for="user-password">Password</label>
<span id="general-error"></span>
<button type="submit" class="submit-btn" id="login-button">Login</button>
<button type="submit" class="submit-btn" id="sign-up">SignUp</button>
Forgot Password?
</div>
</form>
</div>
</body>
</html>
None of the client side JS scripts are interfering with the process either. I did put console.log()'s in all of the other conditions, and there are no clashes either where many res.writeHead() are running simultaneously.
If anyone can find why this is happening?
I tried to use res.setHeader() and res.statusCode() instead of res.writeHead() to see if anything changed, and nothing happened. I tried using promises instead of async/await and that changed nothing either.
###################################
EDIT (Updated with async/await syntax)
###################################
Here is the server code snippet containing more info on where the function is located.
const server = https.createServer(options, async function (req, res) {
// For form submissions
if (req.method.toLowerCase() === "post") {
let body = '';
req.on("data", (chunk) => {
body += chunk.toString();
})
req.on("end", async function () {
// querystring.decode converts browser query string into an object
const userInfo = querystring.decode(body); // userInfo is an object here
// Status code 302 stands for code of redirection
if (req.url.startsWith("/login_page/loginPage.html")) {
const client = createClient();
await client.connect();
let errVal = "";
async function handleLoginReq(req, res) {
// Below is the query to get user password
let dbQuery = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(dbQuery);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
await handleLoginReq(req, res);

Call function in ejs and return mysql data

I have a ejs like this
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="container">
<header>
<%- include('../partials/header'); %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
<% rows.forEach(function (rows) { %>
<tr>
<td><%= rows.tag %>
<div>
<%
var contents = egallery.getContents(rows.tag)
%>
<%= JSON.stringify(contents) %>
</div>
</td>
</tr>
<% }) %>
</div>
</main>
<footer>
<%- include('../partials/footer'); %>
</footer>
</body>
</html>
and a custom js calling mysql and return data
var conn = require('./conn.js');
conn.connect();
function getTags () {
return new Promise((resolve, reject) => {
conn.query(
"Select distinct tag from ray_url",
(err, result) => {
if (err) {
console.log(err);
throw err;
}
return err ? reject(err) : resolve(result)
}
)
})
/*conn.end();*/
}
function getContents (tag) {
return new Promise((resolve, reject) => {
conn.query(
"Select * from ray_url where tag = ?",
[tag],
(err, result) => {
//if (err) {
console.log(result); //i saw data
console.log(err);
//throw err;
//}
return err ? reject(err) : resolve(result)
}
)
})
}
module.exports = {
getTags : getTags,
getContents : getContents
};
i saw the data was printed, but the line var contents = egallery.getContents(rows.tag) , the contents is blank, any one know what is the problem?

Index page in node app only routing to first show page

I'm building a goals app with node/express/psql. When I click on a goal on the index page, I want it to link to the show page for that goal. However, each one is linking to the goal with the id=1. I'm confused because the .forEach I use to print the objects in the first place is working, just not the link. Any help would be appreciated!
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<meta charset="UTF-8">
<title>Goals</title>
</head>
<body>
<h1>Here's a look at all of your goals!!</h1>
New Goal?
<% goals.forEach(goal => { %>
<div class="goal-container">
<h2><%= goal.description %></h2>
<p><%= goal.step1 %></p>
<p><%= goal.step2 %></p>
<p><%= goal.step3 %></p>
<p><%= goal.step4 %></p>
</div>
<% }) %>
</body>
</html>
controller:
const Goal = require('../models/goal');
const goalsController = {};
goalsController.index = (req, res) => {
Goal.findAll(req.user.id)
.then(goal => {
res.render('goals/', { goals: goal });
})
.catch(err => {
res.status(400).json(err);
});
};
goalsController.show = (req, res) => {
Goal.findById(req.params.id)
.then(goals => {
console.log('goals show');
res.render(`goals/show`, { goals:goals })
})
.catch(err => {
res.status(400).json(err);
});
};
module.exports = goalsController;
routes:
const express = require('express');
const goalsController = require('../controllers/goals-controllers');
const goalsRouter = express.Router();
goalsRouter.get('/', goalsController.index);
goalsRouter.get('/new', goalsController.new);
goalsRouter.get('/:id', goalsController.show);
goalsRouter.get('/:id/edit', goalsController.edit);
goalsRouter.put('/:id', goalsController.update);
goalsRouter.post('/', goalsController.create);
goalsRouter.delete('/:id', goalsController.delete);
module.exports = goalsRouter;
model:
const db = require('../db/config');
const Goal = {};
Goal.findAll = id => {
return db.query(`SELECT * FROM goals JOIN users ON goals.user_id = users.id WHERE goals.user_id = $1`, id)
};
Goal.findById = id => {
console.log('findbyId')
return db.oneOrNone(`SELECT * FROM goals WHERE id = $1`, [id])
};
module.exports = Goal;
Thanks in advance!
I believe there is something wrong with your index.ejs
Try replacing <h2><%= goal.description %></h2>
with <h2><%= goal.description %></h2>

In response.write() TypeError: First argument must be string or Buffer

I have created a server in Node and I am calling fb.html through it. Now when I visit http://localhost:8081/ I keep on getting the following error:
http://oi67.tinypic.com/rkde9d.jpg
// server.js
var http = require("http");
var fs = require("fs");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
fs.readFile("fb.html","utf8", function(err, data){
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
response.end();
});
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
// fb.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<script>
var acces_token, object_id=null,id;
// initialize and setup facebook js sdk
window.fbAsyncInit = function() {
FB.init({
appId : 'myappID',
xfbml : true,
version : 'v2.6'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// function to login to facebook
function myFBLogin() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("You are already logged in!");
}
else{
FB.login(function(response){
// user is now logged in
console.log(response);
acces_token=response.authResponse.accessToken;
}, {scope: 'publish_actions' , scope:'user_posts' });
}
});
}
// function to logout
function myFBLogout(){
FB.getLoginStatus(function(response) {
if (response.status === 'unknown') {
alert("You are already logged out!");
}
else{
console.log(response);
FB.logout(function(response) {
// user is now logged out
alert("You are successfully Logged Out!");
acces_token=null;
if(object_id==null)
document.getElementById('status').innerHTML="Post ID is unknown";
else
document.getElementById('status').innerHTML="You are logged out";
});
}
});
}
// function to post an image on wall
function myFacebookPost()
{
FB.api("/me/photos",
'post',
{url: document.getElementById("frm1").elements[0].value},
function (response){
console.log(response);
if(response.error){
if(response.error.code==2500)
{
alert("You are not logged in!");
}
else if(response.error.code==1)
{
alert("Image url is not correct!");
}
else if(document.getElementById("frm1").elements[0].value=="") alert("Enter the URL!");
}
else{
id=response.post_id;
object_id=response.id;
document.getElementById('status').innerHTML=0;
}
}
);
}
//function to count number of likes
function like_count(){
var a=FB.getAuthResponse();
FB.api(
"/"+object_id+"/likes",
'get',
function (response) {
console.log(response);
if(response.error){
if(object_id==null)
{
alert("Object ID is not defined. First create a post!");
}
else if(response.error)
{
alert("You are not logged in!");
}
}
else
document.getElementById('status').innerHTML=response.data.length;
}
);
}
</script>
<button onclick="myFBLogin()">Login to Facebook</button>
<button onclick="myFBLogout()">Logout</button><br><br>
<form id="frm1" action="javascript:myFacebookPost()">
Image URL: <input type="text" name="URL" placeholder="Enter the image url" >
<input type="submit" value="Post Image on Wall" style="display: inline">
</form>
<br>
<button onclick="like_count()" >Likes count</button>
<p style="display: inline">   Likes Count =  </p>
<div id="status" style="display: inline"> Post ID is unknown</div>
</body>
</html>
Please help to find the problem. Well I have that if works fine on systems while on others it raises the above error.

Get socket.id when page reload node Js and Socket.io

near time . I try write chat app using node Js and Socket.io , i have 1 page login.html , 1 page chat.html and server.js file . When i login with UserA, i will send email and pass to server and verify it . After , go to page chat.html . Here , i show list user , but when i try refresh page chat.html , socket.id changed . I have solution save socket.id after refresh in database MongoDb , but when i log in with UserB other browser , and after refresh page of UserA , but socket.id of UserB changed , not User A . Sorry for my English.
This is login.html page
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<body>
<div class="container">
<form class="form-signin" id="formLogin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
jQuery(function ($){
var socket= io.connect('http://localhost:8080');
var $email =$('#inputEmail'),
$password=$('#inputPassword'),
$login=$('#formLogin');
$login.submit(function (event){
socket.emit('login', { email:$email.val(), password:$password.val()});
socket.on('CheckLogin', function (data){
console.log('show something');
if(data){
console.log(data);
window.location.href='chat';
}else {
alert('Tai khoan hoac mat khau khong dung');
}
});
/* ,function (data){
console.log(data);
if(data){
console.log('Login successfuly');
window.location.href = "chat";
socket.on('sendId', function(data){
console.log(data[0]._id);
});
}else {
console.log('Login faile');
}
}*/
event.preventDefault();
});
});
</script>
</body>
</html>
This is server.js file
var app = require('express')(),
server = require('http').Server(app),
io=require('socket.io')(server),
mongoose=require('mongoose');
server.listen(8080);
var mongoURL = 'mongodb://localhost/ChatDatabase';
app.get('/login', function(req, res){
res.sendFile(__dirname+'/signin.html');
});
var emailprecentLogin='';
var namePreLogin = '';
var logInStatus = false;
var Users= mongoose.model('Users',{
email :String,
name:String,
password:String,
socketId :String
});
var Messages = mongoose.model('Messages',{
name :String,
message:String
});
/*list variable*/
var mailLogin = '';
var statusLogin = false ;
var listLogin =[];
mongoose.connect(mongoURL , function(err, db){
if(err){
console.log('Connect err');
}else {
console.log('Connect successfuly');
/*get value send from loginform and verify*/
io.on('connection', function (socket){
socket.on('login', function (data){
var tmpEmail = data.email ;
var tmpPass= data.password ;
mailLogin = data.email;
console.log('info login' + tmpEmail + tmpPass);
Users.findOne({ email:tmpEmail, password:tmpPass }).exec(function(err , docs){
if(docs==null){
console.log(err +typeof(docs));
socket.emit('CheckLogin', false);
}else {
if(docs.email == tmpEmail && docs.password==tmpPass){
statusLogin=true;
socket.emit('CheckLogin', true);
console.log('Info of user login:'+docs + typeof(docs));
app.get('/chat', function (req, res){
res.sendFile(__dirname+'/chat.html');
});
}
}
});
});/*end verify login*/
socket.emit('tmpEmailLogin',mailLogin );
/*update socket id when user f5 or refresh page*/
socket.on('connectServer', function(data){
/*console.log(data);*/
console.log('User F5'+data);
var tmpSocketId = socket.id ;
var tmpLogin = data;
Users.update({email:data},{$set:{socketId:tmpSocketId}},function (err, userUpdate){
if(err){
/*console.log(err);*/
console.log("err sendSocketID");
}else {
Users.find({}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
socket.emit('listUser', docs);
}
});
Users.find({email:mailLogin}).exec(function(err, docs){
if(err){
console.log('Err find list user');
}else {
console.log('Updated socketId');
/*console.log(docs);*/
}
});
}
});
});
/*update socket when user click item*/
socket.on('updateSocketId', function(data){
Console.log('user f5 :' + mailLogin);
});
});
}
});
This is chat.html file
<!DOCTYPE html>
<!-- saved from url=(0040)http://getbootstrap.com/examples/signin/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="http://getbootstrap.com/favicon.ico">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" >
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Chat</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<style type="text/css">
#viewContent{
color: black ;
height: 400px;
background-color: #F5F5F5;
overflow: scroll;
}
#listUser{
height: 400px;
}
</style>
</head>
<body>
<div id='header'>
<h2 class="title">This is chat box</h2>
</div>
<div id='content' >
<div id='listUser' class='col-md-4'>
<li id ='list' class = "list-group-item active">List User</li>
</div>
<div name='chatbox' class='col-md-8'>
<li id ='yourname' class = "list-group-item active">Your Name</li>
<div id='viewContent'></div>
<div name='formInput' >
<form class='' id='formChat'>
<div class="form-group">
<label class="sr-only" for="contentChat">Enter message</label>
<input type="text" class="form-control" id="contentChat" placeholder="Enter message" />
<input type='submit' class='btn btn-primary ' value ='Send'/>
</div>
</form>
</div>
</div> <!-- chat box div -->
</div>
<script type="text/javascript">
jQuery(function($){
var socket = io.connect('http://localhost:8080');
var $contentChat = $('#contentChat'),
$send =$('formChat');
var tmpEmailLogin;
var listID = [];
var idSocket='' ;
var emailPre= '';/*user login precent*/
var tenLogin ='';
var value_id ='';
/*<----------- chat
send list user form server
set connect 2 user
show message
------------->*/
/* socket.on('infoLogin', function(docs){
emailPre=docs ;
});*/
/*send list user */
socket.on('tmpEmailLogin', function(data){
tmpEmailLogin = data;
/*console.log(data);*/
socket.emit('connectServer',tmpEmailLogin); /*gửi socket để set socketId lên database*/
});
/*console.log('user login :' +tmpEmailLogin);*/
socket.on('listUser', function(data){/* show list user in database*/
console.log('socketId listUser :' + socket.id);
var j = 0 ;
/*console.log('Email login:' +emailPre);*/
$('#listUser').empty();
for(var i =0 ; i<data.length; i++){
$('#listUser').append('' +data[i].name+ '');
}
});
var click = 0 ;
$(document).on('click', 'a.list-group-item', function(event){
click ++;
$('#viewContent').innerHTML='';
if(click =1){
$('a.list-group-item').each(function(i , obj){
this.setAttribute("class", " list-group-item");
click = 0 ;
$('#viewContent').empty();
});
}
/*emailLogin=this.id;*/
var reqIdOfEmail = this.id;
this.setAttribute("class", " list-group-item active");
socket.emit('updateSocketId', reqIdOfEmail);
socket.on('ResSocket', function (data){
idSocket = data.idSk;
nameOfSk = data.nameReq ;
console.log(nameOfSk+idSocket );
});
event.preventDefault();
}); /* end click*/
$('#formChat').submit(function(event){
var $contentMsg = $('#contentChat').val();
/*alert($contentMsg);*/
if(idSocket!=''&& idSocket!=null){
socket.emit('SendMsg', {idsocket:idSocket, msg:$contentMsg, name:tenLogin})
}
event.preventDefault();
});
/*P2P message*/
socket.on('P2Pmessage', function (data){
/*var nameReq= data.name;*/
console.log('show something here');
var msgContent=data.content;
$('#viewContent').append('<b></b>'+msgContent +'<br>' );
});
});
</script>
</body>
</html>
You can join your users to same room,
So even if socketId will change
they can send and receive messages.
In connection you join room with this code:
io.on('connection', function(socket){
socket.join('some room');
});
And send message to room:
io.to('some room').emit('some event'):
You can find more documentation here.

Resources