I'm using Node for the first time and am having trouble when a certain response is triggered. In this case, I'm checking if the username and pw matches what I have in DynamoDB. It redirects to my page when the username and pw don't match my db, but when it does, all of my console.log output prints twice (which apparently has something to do with the favicon in Chrome) like "online" and "[pw] + database.js," but it also freezes my IDE and terminal. I then see the "The page isn't working, localhost didn't send any data" error in my browser. Ignore the privacy problems :) Thoughts?
database.js:
var myDB_lookup = function(username, password, route_callbck){
console.log('Looking up: ' + username);
users.get(username, function (err, data) {
if (err) {
route_callbck(null, "Lookup error: "+err);
} else if (data == null) {
route_callbck(null, null);
} else {
// JSON object that stores password & fullname
var value = JSON.parse(data[0].value);
var pw = value.password;
if (pw.valueOf() == password.valueOf()){
route_callbck({ password : pw }, null);
console.log(pw + "database.js");
}else{
//console.log('wrong password');
route_callbck(null, null);
}
}
});
};
routes.js:
var checkLogin = function(req,res){
var user = req.body.username;
var pw = req.body.password;
console.log(user + pw + "routes");
db.lookup(user, pw, function(data, err) {
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}
});
};
main.ejs:
<form method="post" action="/checklogin">
Enter username here: <br>
<input type="text" name="username" placeholder = "Your username"> <br>
Enter password here: <br>
<input type="password" name="password" placeholder = "Your password">
<input type="submit" value="Log In">
</form>
The functions are all linked up in routes.js when I do module.exports = ...
You probably forget to send the response, make sure
res.render() or res.json() or res.send() gets hit
you should put a try/catch around JSON.parse(), that's a best practice.
Looks like your culprit is here:
if (data!=null){
console.log("online");
//req.session.username = user;
//req.session.password = pw;
// you need to send the response here too! <<<<<
res.render('main.ejs'); //// !!!
}else{
res.render('main.ejs',{error:"Fields incorrect"});
}
Related
Can anyone tell my why my login system isn't working on my server? it just returns user not found even though the users table in my mongo DB contains a valid username and password that I use. here is the code I use to try login.
app.post('/dologin', function (req, res) {
console.log(JSON.stringify(req.body))
var uname = req.body.username;
var pword = req.body.password;
db.collection('users').findOne({
"SignIn.username": uname
}, function (err, result) {
if (err) throw err;
if (!result) {
res.redirect('/SignIn');
console.log("user not found :(")
return
}
if (result.SignIn.password == pword) {
req.session.loggedin = true;
req.session.currentuser = uname;
res.redirect('pages/UserAccount')
console.log("a user was recognised, horay!")
} else {
res.redirect('/SignIn')
console.log("user not found :(")
}
});
});
this is the form used to take in the username and password it is stored in a file called SignIn.ejs:
<form action="/dologin" method="POST">
<input class="UsernameBox" type="text" placeholder="username" name="username">
<input class="PasswordBox" type="password" placeholder="password" name="password">
<button class="LogInButton" type="submit">login</button>
</form>
the MongoDB stores its username and passwords in a table called users
I need to get this going in the next day so any help would be greatly appreciated
So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!
I have the following code. So basically the JavaScript needs to look at the username and password and check it via an API (which works) and returns true or false. True giving the user access to the next page and false reloading the login page. Everything works perfectly except for the JavaScript if statement. My code is as follows:
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == "true") {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<input type="text" name="username" id="usr" placeholder="Enter your username">
<input type="password" name="password" id="pass" placeholder="Enter your password">
<button onclick="testAJAX()" id ="login">Login</button>
When JSON data is true or false. Double quotes cannot be used.Thank you for the quick responses. Turns out the problem was that the datatypes are clashing, I changed the API response to 1 and 0 and that seemed to have solved the problem. Easier and more flexible when using numbers.
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == 1) {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
Your code looks fine, except for the type of the success property value.
It could be that the server is not returning a string literal 'true' instead a boolean value true so
if (data.success) { //or data.success === true
window.location = "mainpage.html";
} else {
location.reload();
}
Hello guys i am a newbie when it comes with web development, especially working with node.js, i want to find out how i can receive data sent from client via ajax Post.
below is the script i wrote to post the form data
<script type="text/javascript">
function ecoachSignIn(){
var user = $('#user').val();
var password = $('#pass').val();
var SignIn ={
user : $('#user').val();
pass : $('#pass').val();
};
$.ajax({
type:'POST',
url: 'https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user='+username+'&pass='+password,
data: {
user : $('#user').val();
pass : $('#pass').val();
},
success: function(creditials){
}
});
alert("Hello! your username is "+username+" and password is "+password);
}
this is the form itself
<form style="margin-top:25%; margin-left:30%" method="post" action='/'>
<input class="input" type="text" id="user" required="true" name="username" placeholder="Username">
<input class="button-1" style="background:#000" onClick="ecoachSignIn()" type="submit" value="Log in">
<div style="margin-top:10px">
<input class="input" type="password" id="pass" name="password" required="true" placeholder="Password">
</div>
</form>
node.js server code
router.post('/', function(req, res) {
var request = require("request"),
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
url = req.query.url;//trying to get the url in my jQuery at client side but not working
console.log("Username = "+user_name+", password is "+password);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
status = json_body.status;
success = json_body.msg;
fname = json_body.profile.fname;
console.log("hi "+fname); // Print the username.
console.log("status is "+status); // Print the status.
console.log("success is "+success); // Print the success.
}
}
);
res.end("yes");
});
My major problem is how to process this in node.js backend server
Hope my question is clear ....thanks
Your server side code:
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
Your client side code:
user : $('#user').val();
pass : $('#pass').val();
You call the fields user and pass on the client but username and password on the server. You have to use the same name in both places.
It works when you use the form normally because the name attributes match the names you use the on server.
I am trying an Example from Jump start node.js(chapterote 1 Authentication).I wrote all the program and created all the files and folders witch is needed for chapter 1.For those who dont know Chapter 1 is about using mongolab cloud Service.
form.html
<form action="/signup" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div><input type="submit" value="Sign Up"/></div>
</form>`
lib/db.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports.mongoose = mongoose;
module.exports.Schema = Schema;
// Connect to cloud database
var username = "user"
var password = "password";
var address = ' #dbh42.mongolab.com:27427/nockmarket';
connect();
// Connect to mongo
function connect() {
var url = 'mongodb://' + username + ':' + password + address;
console.log('[*] not reaching here');
mongoose.connect(url);
}
function disconnect() {mongoose.disconnect()}
models/User.js
var db = require('../lib/db');
var UserSchema = new db.Schema({
username : {type: String, unique: true}
, password : String
})
var MyUser = db.mongoose.model('User', UserSchema);
// Exports
module.exports.addUser = addUser;
// Add user to database
function addUser(username, password, callback) {
var instance = new MyUser();
instance.username = username;
instance.password = password;
instance.save(function (err) {
if (err) {
callback(err);
}
else {
callback(null, instance);
}
});
}
When I sumbits the form app hangs and its not calling connect() function witch connects to the mongolab it just waits for finish but nothing happens.
thanks,