Using the resultant request as a variable in my javascript function - javascript

So, i'm using the NPM 'request' library to webscrape the 'URL x'. The '' content inside this 'URL x' is a single line with a youtube video link. So what I'm trying to do is: after my form is submitted, i need to verify the password to match the requirements, than redirect the user to the that youtube video link, inside the '' in the 'URL x', but I don't know how to do it, any ideas ?
// My JS file
var request = require('request');
var url = 'url x';
request(url, function(err, resp, body){
})
function CheckPassword(password){
var psw = /^[a-zA-Z0-9-]\w{1,6}$/;
if (password.value.match(psw)){
alert('Valid password, redirecting ..');
document.location.assign(body);
return false;
}
else{
alert('Invalid password. Try again.');
return true;
}
}
// My form file
<form onsubmit="return CheckPassword(password)">
<div class="form-group">
<label class="password-text" for="password">Password</label><br>
<input id="password" type="password" placeholder="Password" name="password" required >
</div>
<button type="submit" class="form-button">Submit</button>
</form>

Related

Adding User to list after email validation

Tried this a few times but can not get user to add to list after validation
Instructions
PURE JAVASCRIPT
Dynamically add a user to the users list.
Highlight the email input when a user enters an invalid email address and display following message: "please enter a valid email address" in red.
Use the addUser function to submit the user's data.
If the ajax request returns an error, display the error message in red.
Display the newly added user in the users list when the request was successful.
html
<form id = "myForm">
<h2>Add a User:</h2>
<input type="text" name="username" placeholder="name">
<input type="email" name="email" placeholder="email">
<button>add user</button>
<h2>Users:</h2>
<ul id="users"></ul>
Function
// Do not modify this function. Add user service wrapper.
function addUser(username, email, callback) {
var xhr = new XMLHttpRequest();
var response;
var success = (!!Math.round(Math.random()));
if (!success){
response = JSON.stringify({
success: success,
error: "Oups, something went wrong!"
});
} else {
response = JSON.stringify({
success: success,
user: {
username: username,
email: email
}
});
}
xhr.open("POST", "/echo/json/");
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
}
}
xhr.send("json=" + response);
};
jsfiddle http://jsfiddle.net/17e59p4w/2/
My code works as far as email validation but I don't understand how to addUser using the given function

Login problem with mongo dB on my dynamic website using a Linux based codio server

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

Page isn't working error, Node js freezes

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"});
}

Javascript log in using REST

I'm trying to make a login using JavaScript which should check the user authentication using a REST service, using a client in java (for testing) it return a string "hej" if it's successful.
My HTML code:
<div class="login">
<form method="POST">
<h1>Login</h1>
<input type="text" name="username" id="username" placeholder="Username" required><br><br>
<input type="password" name="password" id="password" placeholder="Password" required><br><br>
<input type="submit" name="submit" id="submit" onclick="UserAction()">
</form>
</div>
<script src="load_user.js"></script>
And heres my javascript code (load_user.js)
var username;
var password;
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login", false);
xhttp.setRequestHeader("", User());
xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
$(location).attr('href', url);
}
}
function User(user, pass) {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I want it to change URL when the login is correct, but it just refreshes the page instead.
use with return in onclick="return UserAction()" function and add return false in end of the
UserAction() function .They will prevent the page refresh .
and window.location.href=url is redirect with new page
Changed JavaScript code
var username;
var password;
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login", false);
xhttp.setRequestHeader("", User());
xhttp.send();
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href=url
}
return false; //added to prevent page refresh
}
function User(user, pass) {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
Changed HTML
<div class="login">
<form method="POST" onsubmit="return UserAction()">
<h1>Login</h1>
<input type="text" name="username" id="username" placeholder="Username" required><br><br>
<input type="password" name="password" id="password" placeholder="Password" required><br><br>
<input type="submit" name="submit" id="submit">
</form>
</div>
use window.location.href = "url_here"; to navigate to new page
Use
window.location.href = "http://localhost:8080/FM3/spil2.jsp";
Please do a redirect, after checking the user credentials to change the URL
window.location.replace("http://stackoverflow.com");
or simulate clicking a link like
window.location.href = "http://stackoverflow.com";

How to receive POST form data in node.js from client

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.

Categories