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

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.

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

Using the resultant request as a variable in my javascript function

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>

How to send JSON as respond from Node js to Html file

I'm trying to send JSON from Node js to html file as a response, but after I submit HTML form disapears and this shows up Respond after I submit a form. I tried ajax but it doesn't work beacuse I get redirected to this (image above). I'm trying to make a simple login form and if user inputs nothing then message should get displayed saying "Nothing was input" below the form.
JS code (node.js, express framework)
app.get('/login', function(req, res){
res.sendFile(path.join(__dirname+'/Frontend/html/login.html'));
});
app.post('/login', function(req, res){
res.json({a: 5});
});
html code
<form method="POST">
<input type = "text" name = "username" id = "username" placeholder="Username">
<input type = "password" name = "password" id = "password" placeholder="Password">
<button id = "gumb" type = "submit">Prijavi se</button>
</form>
<p id = "demo"></p>
<script>
document.getElementById('gumb').addEventListener('click', function(){
const xhr = new XMLHttpRequest();
console.log("test");
if(xhr.readyState == 4 && xhr.status == 200){
document.write(xhr.responseText);
}
else{
console.log("broke");
}
xhr.open('get', 'http://localhost:8000/login', true);
});
</script>
Your code works as expected, you just send a json key-value pair to your frontend, when the route is invoked. The data is shown in your browser.
app.post('/login', function(req, res){
res.json({a: 5});
});
Usually, you would want to do something with the data sent to your backend:
app.post('/login', function(req, res){
user= req.body.username;
password = req.body.password;
console.log(`User: ${user} is requesting login`);
// do something with the data - login, save, edit
res.end();
});
Since you obviously commit login data (FROM a form TO your backend),
you should use some authentification middleware to perform a login.
To comfortably send processed html to your backend, you should get acquainted with the subject of views.
And the express api documentation will be very useful to you, I'm sure. ;)
https://expressjs.com/en/api.html

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

Categories