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.
Related
My app works in live server but when i add nodejs, it doesn't work correctly. The Modal window does not pop up anymore and I do not know why. I have understood that I cant use localstorage or window properties because it is not on the browser anymore, but I cant figure out what to do instead of using those. Is there an npm package I can install to use localstorage and other browser side properties? Just looking for someone to point out my mistake and point me in the right direction. Any help is greatly appreciated. Thanks in advance!
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<script src="https://kit.fontawesome.com/4582c8b826.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<title>Issue Tracker</title>
</head>
<body>
<div class="contaienr">
<h1>Issue Tracker</h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueinputform">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select class="form-control" id="issueSeverity">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button id="add-issue" onclick="submitIssue()" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="emptyField" tabindex="-1" role="dialog" aria-labelledby="emptyFieldLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="emptyFieldLabel">Invalid Input!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Please provide the desciption of the issue and also the person name who you want to assign the issue.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
</body>
</html>
app.js
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
if ((description.length == 0) || (assignedTo.length == 0)) {
alert("Please fill all fields with required data.");
document.getElementById('add-issue').setAttribute("data-toggle", "modal");
document.getElementById('add-issue').setAttribute("data-target", "#emptyField")
}
else {
document.getElementById('add-issue').removeAttribute("data-toggle", "modal");
document.getElementById('add-issue').removeAttribute("data-target", "#emptyField")
const issue = { id, description, severity, assignedTo, status };
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
currentIssue.description = `<strike>${currentIssue.description}</strike>`
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => ((issue.id) != id))
localStorage.removeItem('issues');
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (let i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3> ${description} </h3>
<p><i class="fa-solid fa-bolt"></i> ${severity}</p>
<p><i class="fa-solid fa-user"></i> ${assignedTo}</p>
<button onclick="closeIssue(${id})" class="btn btn-warning">Close</button>
<button onclick="deleteIssue(${id})" class="btn btn-danger">Delete</button>
</div>`;
}
}
fetchIssues();
main.js(server)
const bodyParser = require('body-parser');
const express = require('express');
const mongoose = require('mongoose');
const ejs = require('ejs')
const app = express();
const path = require('path');
const morgan = require('morgan')
const bcrypt = require('bcrypt');
const saltRounds = 10;
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('tiny'))
mongoose.connect("mongodb://localhost:27017/userDB", {useNewUrlParser: true});
const userSchema = new mongoose.Schema ({
email: String,
password: String
});
const User = new mongoose.model("User", userSchema)
app.get('/', function(req,res){
// res.sendFile(path.join(__dirname, '/index.html'));
res.redirect('/login')
});
app.get('/login', function (req,res){
// res.sendFile(path.join(__dirname, '/login/login.html'));
res.render('login')
})
app.get('/register', function(req,res){
res.render("register")
});
app.post('/register', function(req,res){
bcrypt.hash(req.body.password, saltRounds, function(err,hash) {
const newUser = new User({
email: req.body.username,
password: hash
});
newUser.save(function(err){
if(err){
console.log(err)
} else{
res.sendFile(path.join(__dirname+'/home.html'));
}
});
});
});
app.get('/home', function(req,res){
res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue()
})
// app.get('/home?', function(req,res){
// // res.sendFile(path.join(__dirname+'/home.html'));
// appSubmit.submitIssue();
// })
app.post('/login', function(req,res){
const username = req.body.username;
const password = req.body.password;
User.findOne({email: username}, function(err,foundUser){
if(err){
console.log(err)
} else{
if(foundUser){
bcrypt.compare(password, foundUser.password, function(err, result) {
// res.sendFile(path.join(__dirname+'/home.html'));
res.redirect('/home')
});
}
}
})
})
app.listen(5000,function(){
console.log("server runnin on 5000")
})
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.
I'm very much not a javascript person, but I've been making an Electron GUI, and I'm getting confused by why I can't seem to make a child browser window call its own js.
I have a main.js that does a bunch of things, setting up a tray menu, one option of which will spawn a browser window like this:
window = new BrowserWindow({
width: 360,
height: 320,
backgroundColor: "#D6D8DC",
show: false
})
window.setMenuBarVisibility(false);
window.loadURL(require('url').format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
And that window loads fine, and includes this reference to its own window.js, which is the way I've seen it done in Electron examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Radiam Agent</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>
<div id="container" class="container-fluid">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Username</h3>
<input name="username" id="username" type="text" size="40"/>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 ">
<h3>Password</h3>
<input name="password" id="password" type="password" size="40"/>
</div>
</div>
<br/><br/>
<div class="button">
<button id="login">Get Radiam Login Token</button>
</div>
</div>
<script src="window.js" charset="utf-8"></script>
</body>
</html>
But the window.js code, which looks like this (the entire file), doesn't seem to fire ever:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login(event) {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("login").addEventListener("click", login(event));
})
Am I missing something? Again, not a js person (I'm building a GUI to a Python script, which is otherwise working great), but it seems like it should be obvious...
Thanks!
This worked. I think it was the wrong type of listener, plus I shouldn't have been trying to pass event:
const notifier = require("node-notifier");
const zerorpc = require("zerorpc");
let client = new zerorpc.Client();
client.connect("tcp://127.0.0.1:4242");
function login() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
client.invoke("login", username, password, function(error, res, more) {
if (res){
notifier.notify({"title" : "Radiam", "message" : res});
}
});
}
document.getElementById("login").addEventListener("click", login);
This is error screen:
express-session deprecated undefined
saveUninitialized option; provide saveUninitialized option
server.js:52:11 listening on port 3000 events.js:167
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'username' of undefined
at User.findOne (C:\Users\aksha\Desktop\kik\passport\passport-local.js:42:32)
at C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\model.js:4187:16
at model.Query.Query._completeOne (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1479:12)
at Immediate.Query.base.findOne.call (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1535:10)
at Immediate.<anonymous> (C:\Users\aksha\Desktop\kik\node_modules\mquery\lib\utils.js:119:16)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5) Emitted 'error' event at:
at C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\model.js:4189:13
at model.Query.Query._completeOne (C:\Users\aksha\Desktop\kik\node_modules\mongoose\lib\query.js:1479:12)
[... lines matching original stack trace ...]
at processImmediate (timers.js:649:5)
I am trying to get user name from ejs file.
This is server.js
const express = require('express');
const bodyParser =require('body-parser');
const ejs = require('ejs');
const http = require('http');
const container = require('./container');
const cookieParser = require('cookie-parser');
const validator = require('express-validator');
const session = require('express-session');
const Mongostore = require('connect-mongo')(session);
const mongoose = require('mongoose');
const flash = require('connect-flash');
const passport = require('passport');
container.resolve(function(users) {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/footballkik',{useMongoClient: true});
const app = SetupExpress();
function SetupExpress(){
const app = express();
const server = http.createServer(app);
server.listen(3000,function(){
console.log('listening on port 3000');
});
ConfigrationExpress(app);
//ROUTER SETUP
const router = require('express-promise-router')();
users.SetRouting(router);
app.use(router);
}
function ConfigrationExpress(app) {
require('./passport/passport-local');
app.use(express.static('public'));
app.use(cookieParser());
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(validator());
app.use(session({
secret:'thisisatest',
resave: true,
saveInitialized: true,
store: new Mongostore({mongooseConnection:mongoose.connection})
}))
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
}
});
This is html file:
<!DOCTYPE html>
<html>
<head>
<title>Xinfin Chat</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="/css/login.css">
</head>
<body>
<div class="container logo-container">
<div class="row">
<div class="col-md-12">
<nav class="navbar" id="nav_bar" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle navbar_icon" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<h1 class="logo-div">
Xinfin Chat
</h1>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li style="padding-right: 50px;">
<h2 class="reg-div">
<a href="/">
Login
</a>
</h2>
</li>
<li class="reg_link2">
<h2 class="reg-div">
<a href="/signup">
Register
</a>
</h2>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
<div id="main">
<div class="main">
<form action="/signup" method="post">
<h1>
Register
</h1>
<div class="inset">
<p>
<label for="username">USERNAME</label>
<input type="text" name="username" class="" placeholder="">
</p>
<p>
<label for="email">EMAIL ADDRESS</label>
<input type="text" name="email" placeholder="" />
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" placeholder="" />
</p>
</div>
<p class="p-container">
<span>Login</span>
<input type="submit" class="login-log" style=" background: #3bb5ec; border: #3bb5ec;" value="Register">
</p>
</form>
</div>
</div>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
This is user.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const userSchema = mongoose.Schema({
username:{type: String, unique: true},
fullname:{type: String, unique: true,default:''},
email:{type: String, unique: true},
password:{type: String, default:''},
userImage:{type: String, default:'default.png'},
facebook:{type: String, default:''},
fbTokens:Array,
goolge:{type: String, default:''},
goolgeTokens:Array
});
userSchema.methods.encryptPassword = function(password) {
return bcrypt.hashSync(password,bcrypt.genSaltSync(10),null);
};
userSchema.methods.validUserPassword = function(password) {
return bcrypt.compareSync(password,this.password);
}
module.exports = mongoose.model('user',userSchema);
This is my passport.js file
'use strict';
const passport = require('passport');
const User = require('../models/user');
const LocalStrategy = require('passport-local').Strategy;
passport.serializeUser((user,done)=> {
done(null, user.id);
});
passport.deserializeUser((id,done)=>{
user.findById(id,(err,user)=>{
done(err,user);
});
});
passport.use('local.signup', new LocalStrategy({
usernameField:'email',
passwordField:'password',
passReqToCallBack: true},(req,email,password,done)=>{
User.findOne({'email':email},(err,user)=>{
if(err){
return done(err);
}
if(user){
return done(null,false,req.flash('error','user email already exist'));
}
const newUser = new User();
newUser.username = req.body.username;
newUser.email= req.body.email;
newUser.password=newUser.encryptPassword(req.body.password);
newUser.save((err)=>{
done(null,newUser);
});
});
}));
As per the error I see and your comment stating that the passport.js has the same code as passport-local.js file.
You are using req.body.username but as per the error, either your req.body is undefined or the newUser is undefined.
Can you add console.log on the req.body for passport.js file and tell me what do you get?
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.");}
});
});