I'm using node.js and mysql for the database. All of my webpages are in .ejs. I have 1 page for customer reviews, I have a form to POST data to my database and then show data from the database as well on the same page. I'm always getting error that a variable is undefined.
app.js
var express = require('express');
var path = require('path');
var app = express();
var mysql = require('mysql');
var connection = require('./dbConfig');
app.set('view engine', 'ejs');
app.use('/public', express.static('public'));
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
//index page
app.get('/', function (req, res,) {
connection.query("SELECT * FROM reviews", function (err, result) {
if (err) throw err;
console.log(result);
res.render('index', {
title: 'customers',
revData: result
});
});
});
app.post('/', function(req, res) {
var name = req.body.rname;
var msg = req.body.rmsg;
console.log(req.body);
var sql = `INSERT INTO reviews (name, message) VALUES ("${name}", "${msg}")`;
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Review submitted!");
})
return res.render('index', { errormessage: 'insert data successfully' });
});
app.listen(process.env.port || 3000);
console.log('Running at Port 3000');
Here's my index.ejs page
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="rev-body">
<div class="rev-form"> <!-- Left column "Review form" -->
<form action="/" method="POST">
<h3>Tell us what you think!</h3>
<input type="text" placeholder="Your name here" name="rname"><br>
<textarea placeholder="Your review here" name="rmsg" maxlength="100" id="form-textarea"></textarea><br>
<div id="rem-char">100 / 100</div>
<button type="submit">Submit</button>
</form>
</div>
<div class="reviews"> <!-- Right column "Customer Reviews" -->
<div class="heading" style="text-align: center"><h1>Customer Reviews</h1></div>
<div class="review-body">
<% if(revData.length!=0) { var i=1; revData.forEach(function(data) {
%>
<div class="cust-comments"><p style="font-weight: bold; font-size: 18px; text-transform: uppercase; margin-bottom: 5px"><%=data.name %></p>
<p style="margin-top:0; font-size: 13px; font-style: italic">"<%=data.message %>"</p></div>
<% i++; }) %> <% } else { %>
<div><h1>No Data Found</h1></div>
<% } %>
</div>
</div>
</div>
</div>
</body></html>
on my index.ejs i always get an error whenever i click the submit button, BUT the data is saved on the database. besides everything else, that is the only error i get.
ReferenceError: C:\database\views\index.ejs:22
20| <div class="heading" style="text-align: center"><h1>Customer Reviews</h1></div>
21| <div class="review-body">
>> 22| <% if(revData.length!=0) { var i=1; revData.forEach(function(data) {
23| %>
24| <div class="cust-comments"><p style="font-weight: bold; font-size: 18px; text-transform: uppercase; margin-bottom: 5px"><%=data.name %></p>
25| <p style="margin-top:0; font-size: 13px; font-style: italic">"<%=data.message %>"</p></div>
revData is not defined
at eval ("C:\\database\\views\\index.ejs":12:8)
at index (C:\database\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\database\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (C:\database\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\database\node_modules\express\lib\view.js:135:8)
at tryRender (C:\database\node_modules\express\lib\application.js:657:10)
at Function.render (C:\database\node_modules\express\lib\application.js:609:3)
at ServerResponse.render (C:\database\node_modules\express\lib\response.js:1039:7)
at C:\database\app.js:41:13
at Layer.handle [as handle_request] (C:\database\node_modules\express\lib\router\layer.js:95:5)
I've used all of my resources for about a week now and don't know why it's getting that error when that "revData" is already declared on the app.get
I tried declaring a variable in the ejs page with
<% var revData = []; %>
and the error goes away, but now the data does not show on the web page.
Hope someone can help me with this, this is my first time using node.js and still currently studying it.
Related
I'm having a weird issue with EJS when I use res.render to try and pass the javascript object (key:value).
For example, this works just fine (having two separate app.get requests work's great):
///////////root route
app.get("/", function (req, res) {
Featuredblog.find({}, function (err, blogs) {
if (err) {
console.log(err);
} else {
res.render("home", { blogs: blogs });
}
});
});
////////GET FEATURED VIDEO PAGE SECTION
app.get("/featuredvideo", function (req, res) {
Featuredpost.find({}, function (err, videos) {
if (err) {
console.log(err);
} else {
res.render("featuredvideo", { videos: videos });
}
});
});
But I don't want the Featured Videos to be on a separate page. I want them to be on the home page along with the featured blog posts.
But when I go to combine them into the app.get("/") request, it gives EJS Reference Error saying "videos" is not defined at eval (eval at compile...
Here is what it looks like when I combine them:
app.get("/", function (req, res) {
Featuredblog.find({}, function (err, blogs) {
if (err) {
console.log(err);
} else {
res.render("home", { blogs: blogs });
}
});
Featuredpost.find({}, function (err, videos) {
if (err) {
console.log(err);
} else {
res.render("home", { videos: videos });
}
});
});
It has no problem with passing "blogs"key value, it's only the "videos" key that gives me trouble. Also, when I console.log("Success") after for the else statement, it logs "Success", so the function works.
Both my home.ejs and featuredvideos.ejs files are in my "views" folder.
Here is what my home.ejs file looks like:
<!-- featured blog section -->
<div class="container-fluid">
<h1 class="video-title">Featured Blogs</h1>
<% blogs.forEach(function(blog) { %>
<div class="video-container">
<div class="video">
<div class="blog-image">
<img src="/images/<%= blog.image %>">
</div>
</div>
<div class="video video-text">
<h1> <%= blog.title %> </h1>
<p>
<%= blog.content.substring(0, 700) %> ... <mark>Read More.</mark>
</p>
</div>
</div>
<% }); %>
</div>
<!-- featured Videos section -->
<div class="container-fluid">
<h1 class="video-title">Featured Videos</h1>
<% videos.forEach(function(video) { %>
<div class="video-container">
<div class="video">
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="<%= video.video %>" allowfullscreen></iframe>
</div>
</div>
<div class="video video-text">
<h1> <%= video.title %> </h1>
<p>
<%= video.content.substring(0, 700) %> ... <mark>Read More.</mark>
</p>
</div>
</div>
<% }); %>
</div>
And this is the error I get:
ReferenceError: /Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/views/home.ejs:47
45|
46|
>> 47| <% videos.forEach(function(video) { %>
48|
49| <div class="video-container">
50| <div class="video">
videos is not defined
at eval (eval at compile (/Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/node_modules/ejs/lib/ejs.js:649:12), <anonymous>:26:8)
at home (/Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/node_modules/ejs/lib/ejs.js:679:17)
at tryHandleCache (/Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/node_modules/ejs/lib/ejs.js:272:36)
at View.exports.renderFile [as engine] (/Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/node_modules/ejs/lib/ejs.js:478:10)
at View.render (/Users/Louieg3/Documents/WEB DEVELOPMENT/mindunravelledexpress/node_modules/express/lib/view.js:135:8)
at tryRender (/Users/Louieg3/Documents/WEB ... etc.
Any thoughts? I'm not sure why it would work when it's broken out into a separate app.get request, vs being part of the root route get request. I can't see anything online about having two separate functions giving a problem with EJS and Node.
Thanks in advance,
I have problem with locals. In post model I have comments collection, everything is fine and without problems get user and post id but I can't output in views username and user avatar from post.postComments[i].author.username/avatar ( look below in index.js ). What could be a problem ?
PostController.js
index: function(req, res){
Post.find({}).populate('author').populate('postComments').exec(function(err, results) {
res.send(200, results);
});
},
addComment: function(req, res){
var params = req.allParams();
Comment.create({author: params.author, content: params.content, post: params.post, postId: params.postId}, function(err, comment){
if (err){ res.send(500, err); console.trace(err); }
else{
res.send(200, comment);
res.redirect("/");
console.log("Testt");
}
});
},
index.ejs
<form action="/addComment" method="POST">
<div class="row">
<div class="col-10 col-sm-11 col-md-11">
<input type="hidden" name="author" value="<%= req.user.id %>">
<input type="hidden" name="postId" value="<%= post.id %>">
<input type="text" id="postcomment" name="content" placeholder="Comment here..">
</div>
<div class="col-1 col-sm-1 col-md-1">
<button type="submit"><i class="fas fa-location-arrow" style="color: #0c5460; font-size: 23px; margin-left: -10px;"></i></button>
</div>
</div>
<% if(post.postComments.length > 0) { %>
<% for(var i = 0; i < post.postComments.length; i++) { %>
<div id='<%- post.postComments[i].id%>'>
<div style="padding-top: 10px;">
<div class="container" style="background-color: #ccc; border-radius: 20px;">
<div class="row">
<div class="col-md-1" style="padding: 0;">
<img src='/images/profileimage/<%- post.postComments[i].author.profileimage_uid %>' style="width: 30px; height: 30px; border-radius: 80px; border: 1px solid #ccc;">
</div>
<div class="col-md-2" style="padding: 3px; margin: inherit;">
<%- post.postComments[i].author %>
</div>
<div class="col-md-7" style="padding: 4px; word-break: break-all;">
<p>- <%- post.postComments[i].content%></p>
</div>
</div>
</div>
</div>
</div>
<% } %>
<% } %>
I'm doing some guessing based on limited code in your question, but...
If this is the line that fetches your data to add to your view:
Post.find({}).populate('author').populate('postComments')
and if the Author of a post Comment is a linked collection, then the problem is that your author is not populated into your post comments. You populate your Post with the Comments, but never go on to populate the Comments with their Author
Apologies if I'm guessing wrong about your data storage.
EDIT
If you want to know how to implement the two-level "nested" populate you are trying to do... sails does not do this out of the box, you have to write the code yourself. Here's one way, starting by fetching a user dictionary:
User.find({}).exec(function(err,users) {
// handle any error
var userDict = {};
for (var i = 0; i < users.length; i++) {
userDict[users[i].id] = users[i];
}
// now fetch your posts
Post.find({}).populate('postComments').exec(function(err, posts) {
// handle any error
// now use your user dictionary to populate
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
if (post.author && userDict[post.author]) {
post.author = userDict[post.author];
}
for (var j = 0; j < post.postComments.length; j++) {
var comment = post.postComments[j];
if (comment.author && userDict[comment.author]) {
comment.author = userDict[comment.author];
}
}
}
return res.send(200, posts);
});
});
This is pretty ugly, but something like this may be required if you want this two-level population. Some thoughts:
You can flatten the callbacks some if you're able to use a promise library.
If you have a very large number of users, you may decide to build your user dictionary after getting your posts and fetch just the ones you need.
I refactored my code and broke some things out into models to simplify my app.js file. And once I did that, I started getting errors that items inside the req.body object are undefined. I can't, for the life of me, figure out why.
I've tried Googling the solution, searching on Stackoverflow, and reading my code about 5,000 times to find the problem, but to no avail.
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
expressSanitizer = require("express-sanitizer"),
mongoose = require('mongoose'),
Job = require("./models/job"),
Worker = require("./models/worker"),
Boss = require("./models/boss");
mongoose.connect("mongodb://localhost/tiny_gig", { useNewUrlParser: true });
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(expressSanitizer());
app.use(methodOverride("_method"));
// CREATE ROUTE
app.post("/jobs", function(req,res){
req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- This works just fine.
// Create job
Job.create(req.body.job, function(err, newlyCreated){
if(err){
res.render("new");
} else {
res.redirect("/jobs");
}
});
});
// SHOW ROUTE
app.get("/jobs/:id", function(req, res) {
// Find the job with the specific ID
console.log(req.body);
Job.findById(req.params.id, function(err, foundJob){
if(err){
res.redirect("/jobs");
} else {
res.render("show", {job: foundJob});
}
});
});
// EDIT ROUTE
app.get("/jobs/:id/edit", function(req, res) {
req.body.job.jobInfo = req.sanitize(req.body.job.jobInfo); // <--- If I comment this line out, everything works...
Job.findById(req.params.id, function(err, foundJob){
if(err){
res.redirect("/jobs");
} else {
res.render("edit", {job: foundJob});
}
});
});
Here are the EJS templates:
// EDIT TEMPLATE
<% include partials/header %>
<div class="ui main text container segment">
<div class="ui huge header">Edit "<%= job.title %>" </div>
<form class="ui form" action="/jobs/<%= job._id %>?_method=PUT" method="POST">
<div class="field">
<input type="text" name="job[title]" value="<%= job.title %>">
</div>
<div class="field">
<input type="text" name="job[preview]" value="<%= job.preview %>">
</div>
<div class="field">
<textarea required name="job[jobInfo]"><%= job.jobInfo %></textarea>
</div>
<div class="field">
<input class="ui teal basic button" type="submit">
</div>
</form>
</div>
// SHOW TEMPLATE
<% include partials/header %>
<div class="ui main text container ">
<div class="ui huge header"><%= job.title %></div>
<div class="ui top attached segment">
<div class="item">
<div class="description">
<p><%=job.jobInfo%></p>
<div class="content">
<span><small>Created on: <em><%= job.created.toDateString() %></em></small></span>
</div>
<a class="ui teal basic button" href="/jobs/<%= job._id %>/edit">Edit</a>
<form id="delete" action="/jobs/<%= job._id %>?_method=DELETE" method="POST">
<button class="ui red basic button">Delete</button>
</form>
</div>
</div>
</div>
</div>
\\ JOBS MODEL
`code`
var mongoose = require("mongoose");
// JOB SCHEMA SETUP
var jobSchema = new mongoose.Schema({
title: String,
preview: String,
jobInfo: String,
created: {type: Date, default: Date.now}
});
module.exports = mongoose.model("Job", jobSchema);
ERROR I'm getting
TypeError: Cannot read property 'jobInfo' of undefined
at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/app.js:71:53
at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:281:22
at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:354:14)
at param (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:365:14)
at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:410:3)
at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)
at methodOverride (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/method-override/index.js:65:14)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:317:13)
at /home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:335:12)
at next (/home/ubuntu/workspace/TinyGig/TinyGig v2.semanticUI/node_modules/express/lib/router/index.js:275:10)
req.body is available only for post request not get request
your view and edit urls are registered as get request. You can use req.query to access url parameters
app.get("/jobs/:id", function(req, res) {
app.get("/jobs/:id/edit", function(req, res) {
Above lines needs to be modified
Use app.post() or change req.body to req.query to access URL parameters.
There is a simple express.js app , which has to connect to the mysql database and then gets the information from the user for registering in database . although the app connects to the database correctly , but no action has been performed on the register button click . Here is my code
App.js
var express = require("express");
var login = require('./routes/register');
var bodyParser = require('body-parser');
var app = express();
app.use(express.static(__dirname + "/static"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var path = require('path');
//app.set('views', path.join(__dirname, 'static/views'));
//app.use('/scripts', express.static(path.join(__dirname, 'node_modules')));
//app.use(express.static(path.join(__dirname, 'static')));
var engines = require('consolidate');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
var router = express.Router();
app.get('/',function (req,res) {
res.sendFile(__dirname + '/static/register.html');
});
router.post('/register',register.register);
app.use('/api', router);
app.listen(5000);
register.js
var express = require("express");
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'CREBA'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
exports.register = function(req,res){
// console.log("req",req.body);
var USER={
"NAME":req.body.firstname,
"FAMILY":req.body.lastname,
"ID":req.body.personaly,
"POS":req.body.position
}
connection.query('INSERT INTO USER SET ?',USER, function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
console.log({
"code":400,
"failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
console.log({
"code":200,
"success":"user registered sucessfully"
});
}
});
}
HTML :
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Node Js APP</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/home.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/home.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<h1 id="header">Node JS APP</h1><span id="auth" class="label label-info"> -- </span>
<div id="authBox">
<div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%">
<h3> Login </h3>
<div> <span>first</span><input class="form-control" id="firstname"> </div>
<div> <span>last</span> <input class="form-control" id="lastname"> </div>
<div> <span>last</span> <input class="form-control" id="personaly"> </div>
<div> <span>last</span> <input class="form-control" id="position"> </div>
<button style="margin: 5px" class="btn btn-primary" id="register"> register </button>
</div>
<div style="width: 40% ; margin: auto ; display: inline-block ; margin-left: 5%" >
<h3> Sign Up </h3>
<div><span> Username</span><input class="form-control" id="signUpUser"> </div>
<div><span> Password </span> <input class="form-control" id="signUpPass"> </div>
<button style="margin: 5px" class="btn btn-primary" id="signUp"> Sign Up !</button>
</div>
</div>
</div>
</div>
<div class="alert alert-danger" style="text-align: center ; "></div>
<div class="alert alert-success" style="text-align: center ;"></div>
<div style="text-align: center ; border: 1px solid #e2e2e2 ; margin: 20px " id="cmBox">
<div style="width:75% ; padding: 20px ; margin: auto "><span> Enetr Comment: </span> <input class="form-control" id="msg"> </div>
<button class="btn btn-success" id="submitComment"> Submit </button>
<ul id="commentBox" class="list-group" style="margin: 25px 20%">
</ul>
</div>
home.js
$(document).ready(function () {
var isAuth = false ;
var errorBox = $("div.alert-danger") ;
var successBox = $("div.alert-success") ;
successBox.slideUp(1);
errorBox.slideUp(1);
console.log(successBox);
$("#register").click(function () {
console.log({ firstname : $("#firstname").val() ,lastname : $("#lastname").val() , personaly : $("#personaly").val() ,POS : $("#POS").val() }) ;
$.post("/register" , { username : $("#firstname").val() ,password : $("#lastname").val ,( "#personaly").val() ,POS : $("#POS").val() } , function (data) {
if (data['status']) {
successBox.slideUp(1);
errorBox.slideUp(1);
successBox.html(data['msg']).slideDown(500) ;
getInfo() ;
}
else {
successBox.slideUp(1);
errorBox.slideUp(1);
errorBox.html(data['msg']).slideDown(500) ;
getInfo() ;
}
})
}) ;
getInfo() ;
}) ;
I suspect you have a 404 Not found ;) (not sure though, but from what I can see).
These lines in your express app:
router.post('/register',register.register);
app.use('/api', router);
I haven't work with express for a while, but from my recollection, it means that in your client application, you should call /api/register and not /register.
Try this: $.post("/api/register" ... in your home.js file.
Moreover, watchout:
Your post handler in the express server reads the position parameter this way:
req.body.position
but the client sends it in POS, not position, so, the position value will likely always be undefined in your server.
I am developing basic application that has a simple membership. Besides, i need to develop Sessions aswell. In my following code, sockets do not respond. Can you help me to find the reason behind that ?
app.js
var WebApp = require('./webApp.js');
var db = require('./db/db.js');
var db = new db();
var webApp = new WebApp();
var App = function(){}
webApp.initialize();
webApp.socketIOConnect(function(client){
webApp.socketIOConnectMethods(client);
});
module.exports = App;
webApp.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var socketHandshake = require('socket.io-handshake');
var io = require('socket.io')(server);
io.use(socketHandshake({secret:'secret',resave : false, saveUninitialized : true, parser:cookieParser()}));
server.listen(1185);
var WebApp = function () {
console.log("Greetings from WebApp Module.");
}
var db = new Db();
WebApp.prototype.initialize = function () {
app.use(express.static("./assets"));
router.get('/', function (req, res, next) {
res.sendFile("./assets/index.html");
});
router.get('/login', function (req, res, next) {
res.sendFile(path.resolve("./assets/login.html"));
});
router.get('/client', function (req, res, next) {
res.sendFile(path.resolve("./client/client.html"));
});
app.use(router);
}
WebApp.prototype.socketIOConnect = function(callback) {
io.on('connection', function(client, req, res) {
callback(client)
});
}
WebApp.prototype.socketIOConnectMethods = function (client) {
if (client.handshake.session.name) {
console.log('We already know you!');
client.emit('get name');
client.emit('redirect');
};
client.on('join', function(data) {
console.log(data);
});
client.on('register', function(data) {
client.emit('username', data);
console.log(data);
var checkAuth;
var username = data.user;
var password = data.passw;
var email = data.email;
var confpass = data.confirmPass;
console.log("password : "+password);
console.log("conf password :"+confpass);
if ( password == confpass){
console.log("Passwords match, this lad can login");
var values = [[, username, password, email]];
console.log(username + " " + password + " " + email);
db.registAuth(email,function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
client.on('passwordmatches',function(data){
console.log(data);
});
console.log(results);
var checkAuth = results.length;
if(results < 1){
db.userRegistration(values,function(err, results) {
if(err) {
console.log("An error occurred: " + err.message);
}
console.log(results);
});//user registration
}
else{console.log("Sorry, we could not complete your registration. Email already exists.");}
});//registAuth
}
else{
client.on('NoMatchPass',function(data){
console.log(data);
});
console.log("Sorry, we could not complete your registration. Passwords do not match !");
client.emit('tryagainreg',"Sorry, we could not complete your registration. Passwords do not match !");
}
});//client.on register
client.on('login', function(data) {
var email = data.email;
var password = data.password;
console.log(data);
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
client.handhsake.session.name = email;
client.handshake.session.save();
console.log(client.handshake.session.name);
client.emit('AuthLogin',email);
}
else{console.log("Wrong username or password.");
client.emit('FailedLogin',email);
}
});
});
};
module.exports = WebApp;
I want user to login when they completed their registration successfully and then, when they logged in successfully i want to redirect them client.html but with session so that i can keep them authorized till they logged out of the applicaton.
login.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
<link rel="icon" type="image/png" href="../assets/img/favicon.png">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>Let's Get Head In</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<!-- Fonts and icons -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
<!-- CSS Files -->
<link href="./css/bootstrap.min.css" rel="stylesheet" />
<link href="./css/material-kit.css" rel="stylesheet"/>
</head>
<body class="signup-page">
<nav class="navbar navbar-transparent navbar-absolute">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-example">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="">AslanServices</a>
</div>
<div class="collapse navbar-collapse" id="navigation-example">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="./index.html" target="">
Register
</a>
</li>
<li>
<a href="" target="">
<i class="material-icons">unarchive</i>Contact
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="wrapper">
<div class="header header-filter" style="background-image: url('./img/city.jpg'); background-size: cover; background-position: top center;">
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3">
<div class="card card-signup">
<form class="loginform" method="" action="">
<div class="header header-primary text-center">
<h4>Sign In</h4>
</div>
<div class="content">
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<input type="text" class="form-control" id="email" placeholder="Email...">
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock_outline</i>
</span>
<input type="password" placeholder="Password..." id="password" class="form-control" />
</div>
<!-- If you want to add a checkbox to this form, uncomment this code
<div class="checkbox">
<label>
<input type="checkbox" name="optionsCheckboxes" checked>
Subscribe to newsletter
</label>
</div> -->
</div>
<div class="footer text-center">
<button type="submit" class="btn" value="Submit">Sign in!</button>
</div>
</form>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<nav class="pull-left">
<ul>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
AslanServices
</a>
</li>
<li>
<a href="https://www.instagram.com/ozercevikaslan/">
About Us
</a>
</li>
</ul>
</nav>
<div class="copyright pull-right">
© 2017, made by Aslanmeister
</div>
</div>
</footer>
</div>
</div>
</body>
<!-- Core JS Files -->
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="./js/bootstrap.min.js" type="text/javascript"></script>
<script src="./js/material.min.js"></script>
<!-- Plugin for the Sliders, full documentation here: http://refreshless.com/nouislider/ -->
<script src="./js/nouislider.min.js" type="text/javascript"></script>
<!-- Plugin for the Datepicker, full documentation here: http://www.eyecon.ro/bootstrap-datepicker/ -->
<script src="./js/bootstrap-datepicker.js" type="text/javascript"></script>
<!-- Control Center for Material Kit: activating the ripples, parallax effects, scripts from the example pages etc -->
<script src="./js/material-kit.js" type="text/javascript"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('127.0.0.1:1185');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
socket.on('redirect',function(callback){ callback(window.location.href="127.0.0.1:1185/client");
});
$('form.loginform').submit(function(event){
event.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
socket.emit('login',{email : email, password : password});
socket.on('AuthLogin',function(data){window.location.href = 127.0.0.1:1185/client";});
socket.on('FailedLogin',function(data){alert('Wrong username or Password. Maybe, you dont even exist!');window.location.href = "127.0.0.1:1185";});
});
});
</script>
</html>
I simply solved my problem by using this code below.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var router = express.Router();
var path = require('path');
var Db = require('./db/db.js');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(cookieParser('aslan'));
var redis = require("redis");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var io = require('socket.io')(server);
var cookie = require('cookie');
//var passwordHash = require('password-hash');
var redisclient = redis.createClient();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true }));
var sessionMiddleware = session({
store: new RedisStore({host : 'localhost' , port : '6379' , client : redisclient , ttl : 15}), // redis server config
secret: 'aslan',
resave : false,
saveUninitialized : false
});
app.use(sessionMiddleware);
//---------------CONFIG PART ENDED-------------
app.get('/',function (req, res, next) {
session = req.session;
if ( session.key ){
res.redirect('/'+session.key+'');
}
res.sendFile("./assets/index.html");
});
//---------------------------------
app.get('/login', function (req,res,next) {
session = req.session;
if ( session.key ){
if ( session.key == 'admin#gmail.com'){res.redirect('/admin');}
if ( session.key != 'admin#gmail.com'){res.redirect('/'+session.key);}
}
res.sendFile(path.resolve("./assets/login.html"));
});
//--------------------------------LOGIN POST------------------
app.post('/login', function (req,res,next) {
console.log("hi from login post");
var email = req.body.user.email;
var password = req.body.user.password;
db.loginAuth(email, password, function(err, results) {
if (err) {
console.log("An error occurred: " + err.message);
}
console.log(results.length);
if ( results.length == 1){
console.log("Welcome, "+email+"!");
//session
session = req.session;
session.key = email;
db.returnUsername(session.key,function(err,result){
if (err) {
console.log('An Error Occured in Db :' + err.message);
}
console.log(result);
console.log(session.key+'Before checking');
if ( session.key == 'admin#gmail.com'){console.log('Session key is equal to admin#gmail.com'); res.redirect('/admin');}
if ( session.key != 'admin#gmail.com'){console.log('Session key is not equal to admin#gmail.com'); res.redirect('/evsahibi');}
});
}
else{console.log("Wrong username or password.");}
});
});