I want to add a new user to mysql database and I know how to make querys with one unique search row but now I got four of them.
4 inputs
<div id="data">
User:
<input type="text" name="UserName" id="name_u"></textarea>
<br>
Password:
<input type="password" name="contraseƱa" id="pass_u">
<br>
Email:
<input type="email" name="email" id="email_u">
<br>
BirthDate:
<input type="date" name="BirthDate" id="bday_u">
<br>
<input value="Registrar" type="button" onclick="add_u()">
</div>
My problem is that I don't know how to make the AJAX and write the js to make them work.
app.get ('/useradd',(req, res)=>{
var name_u = req.query.name_u;
var pass_u = req.query.pass_u;
var email_u = req.query.email_u;
var bday_u = req.query.bday_u;
mysqlConnection.query('INSERT INTO user (UserName, Password, email, BirthDate, level, U_rank) VALUES ()', [search], (err, rows, fields)=>{
if (!err){
console.log(rows);
res.end(rows);
}
else
console.log(err);
})
});
This is the code I'm ussing on my js.
If someone can help me I'll really appreciate it.
Wrap your inputs in < form > not a < div >
<form method="POST" enctype="multipart/form-data" id="myform">
<input type="text" name="title"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<h1>jQuery Ajax Post Form Result</h1>
<span id="output"></span>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
Use next javascript to collect and send form data
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#myform')[0];
// Create an FormData object
var data = new FormData(form);
// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 800000,
success: function (data) {
$("#output").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#output").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
Related
I am working on a website with MongoDB, Node.js and Express (no React or Angular). I have the user registration working fine. But my login is not working and I cannot figure out why. Below I post the relevant code:
index.js
/*
* Login Existing User
*/
const loginController = require("./controllers/login")
app.get('/auth/login', loginController);
const loginUserController = require('./controllers/loginUser')
app.post('/users/login', loginUserController)
/controllers/login:
module.exports = (req, res) => {
res.render('login')
}
relevant portion of login.ejs (which is rendered due to preceding code):
<form action="/users/login" method="POST" enctype="multipart/form-data">
<div class="form-floating">
<input class="form-control" id="username" type="text" placeholder="User Name" data-sb-validations="required" name = "username"/>
<label for="title">Username</label>
<div class="invalid-feedback" data-sb-feedback="title:required">A descriptive title is required.</div>
</div>
<div class="form-floating">
<input class="form-control" id="password" type="password" placeholder="Password" data-sb-validations="required" name="password"/>
<label for="name">Password</label>
<div class="invalid-feedback" data-sb-feedback="name:required">Password required.</div>
</div>
<br />
<!-- This is what your users will see when there is-->
<!-- an error submitting the form-->
<div class="d-none" id="submitErrorMessage"><div class="text-center text-danger mb-3">Error sending message!</div></div>
<!-- Submit Button-->
<button class="btn btn-primary text-uppercase" id="submitButton" type="submit">Login</button>
</form>
/controllers/loginUser:
const bcrypt = require('bcrypt')
const User = require('../models/User')
module.exports = (req,res) =>{
const { username,password } = req.body
User.findOne({username: username}, (error,user) => {
if(user){
bcrypt.compare(password, user.password, (error,same)=>{
if(same){
req.session.userId = user._id
res.redirect('/')
}
else{
res.redirect('/auth/login')
}
})
}
else{
console.log("/auth/login::",user)
res.redirect('/auth/login')
}
})
}
I have used Postman and also just tested in Chrome and Firefox and it appears that the GET made to /auth/login appears to work. I get there and I submit my form. But instead of redirecting me to my index or landing page ("/"), it just sends me back to /users/login and, also, the website doesn't recognize that I am logged in. Here is my code to trigger a Boolean if I am logged in:
global.loggedIn = null;
app.use("*", (req, res, next) => {
loggedIn = req.session.userId;
next()
});
Any thoughts/suggestions as to what I am doing wrong are appreciated.
Problem Description : I am trying to integrate payuMoney in a website which uses ReactJS NodeJS and express. I have a form for taking inputs from the user. What I'm trying to do is pass the data from react form to API which is in index.js where we request the test PayuMoney URL i.e. https://sandboxsecure.payu.in/_payment and get a body in response which is the HTML code for the payment page.
What I'm trying to achieve: Take the input data from user, feed it to the backend API, where I'll add another private keys and generate a hash string. Request the PayuMoney test URL i.e. https://sandboxsecure.payu.in/_payment with the form and redirect to it and make the payment.
I have tried three methods here.
First is directly sending data from the frontend to the test URL using
<form action="https://sandboxsecure.payu.in/_payment" method="POST" > -- This case work fine but is dangerous because it would expose private keys
Second is sending the post request to backend API using <form action="/api/payumoney" method="POST" > -- This one redirects to the payment page but does not send the data from the form to the backend.
Third is using axios/fetch POST request to the "api/payumoney" using a handler function which uses e.preventDefault() -- This one sends the data to the backend and even makes a request to the PayuMoney Test URL but doesn't redirect to the payment page.
App.js
function handleClick(e) {
var pd = {
key: formValue.key,
salt: formValue.salt,
txnid: formValue.txnid,
amount: formValue.amount,
firstname: formValue.firstname,
lastname: formValue.lastname,
email: formValue.email,
phone: formValue.phone,
productinfo: formValue.productinfo,
service_provider: formValue.service_provider,
surl: formValue.surl,
furl: formValue.furl,
hash: ''
};
axios.post("/api/payumoney",{
pd
}).then((res)=> {
console.log(res);
}).catch((error)=>{
console.log(error);
});
}
return (
<div className="App">
<form onSubmit={handleClick} method="POST" action="/api/payumoney">
<label>
FirstName:
<input type="text" name="firstname" onChange={handleChange} value={formValue.firstname} />
</label>
<label>
TxnID:
<input type="text" name="txnid" onChange={handleChange} value={formValue.txnid} />
</label>
<label>
Amount:
<input type="text" name="amount" onChange={handleChange} value={formValue.amount} />
</label>
<label>
ProductInfo:
<input type="text" name="productinfo" onChange={handleChange} value={formValue.productinfo} />
</label>
<label>
Email:
<input type="email" name="email" onChange={handleChange} value={formValue.email} />
</label>
<label>
Phone:
<input type="text" name="phone" onChange={handleChange} value={formValue.phone} />
</label>
<label>
Hash:
<input type="text" name="hash" onChange={handleChange} value={formValue.hash} />
</label>
<input type="hidden" id="key" name="key" value="MERCHANTKEYVALUE"></input>
<input type="hidden" id="salt" name="salt" value="MERCHANTSALT"></input>
<input type="hidden" id="surl" name="surl" value="/payment/success"></input>
<input type="hidden" id="furl" name="furl" value="/payment/fail"></input>
<input type="submit" value="Submit" />
</form>
</div>
);
index.js
app.post("/api/payumoney",(req,res) => {
if (!req.body.txnid || !req.body.amount || !req.body.productinfo || !req.body.firstname || !req.body.email) {
res.status(400).json("Mandatory fields missing");
}
var pd = req.body;
var hashString = pd.key + '|' + pd.txnid + '|' + pd.amount + '|' + pd.productinfo + '|' + pd.firstname + '|' + pd.email + '|' + '||||||||||' + pd.salt; // Your salt value
var sha = new jsSHA('SHA-512', "TEXT");
sha.update(hashString);
var hash = sha.getHash("HEX");
pd.hash = hash;
request.post({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://sandboxsecure.payu.in/_payment', //Testing url
form: pd,
}, function (error, httpRes, body) {
if (error){
console.log("Error",error);
res.status(400).json(
{
status: false,
message: error
}
);
}
if (httpRes.statusCode === 200) {
res.send(body);
} else if (httpRes.statusCode >= 300 &&
httpRes.statusCode <= 400) {
res.redirect(httpRes.headers.location.toString());
console.log("error 300 and 400");
}
})
})
I'm using proxy to have the same origin for both the client and server endpoints.
Thanks :)
Solution :
Add body-parser
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post("/api/payumoney", urlencodedParser, (req,res) => {
console.log(req.body);
}
So I have a form and in the form i ask the user to enter his phone number to be verified, and then his information will be inserted into DB with PHP queries.
I used this code:
var firebaseConfig = {
apiKey: "******",
authDomain: "*****",
databaseURL: "https://****",
projectId: "*****",
storageBucket: "",
messagingSenderId: "*****",
appId: "1:****:*****"
};
firebase.initializeApp(firebaseConfig);
// Create a Recaptcha verifier instance globally
// Calls submitPhoneNumberAuth() when the captcha is verified
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "normal",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
// This function runs when the 'sign-in-button' is clicked
// Takes the value from the 'phoneNumber' input and sends SMS to that phone number
function submitPhoneNumberAuth() {
var phoneNumber = document.getElementById("phoneNumber").value;
var appVerifier = window.recaptchaVerifier;
firebase
.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function(confirmationResult) {
window.confirmationResult = confirmationResult;
})
.catch(function(error) {
console.log(error);
});
}
// This function runs when the 'confirm-code' button is clicked
// Takes the value from the 'code' input and submits the code to verify the phone number
// Return a user object if the authentication was successful, and auth is complete
function submitPhoneNumberAuthCode() {
var code = document.getElementById("code").value;
confirmationResult
.confirm(code)
.then(function(result) {
var user = result.user;
console.log(user);
})
.catch(function(error) {
console.log(error);
});
}
//This function runs everytime the auth state changes. Use to verify if the user is logged in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log("USER LOGGED IN");
} else {
// No user is signed in.
console.log("USER NOT LOGGED IN");
}
});
to verify the user's phone number. and in the form i used this :
<div class="verifyCon">
<div class="SMSBox Padding2">
<div>
<span class="Text3"> phone number </span>
</div>
<div>
<input class="InptText" type="tel" id="phoneNumber" maxlength="10" minlength="10" name="uphone" required>
</div>
<div>
<button type="button" class="SMSBut" onclick="submitPhoneNumberAuth()">
<h2 id="sign-in-button" class="Text2"> send </h2>
</button>
</div>
</div>
<div class="SMSBox Padding2">
<div>
<span class="Text3"> code </span>
</div>
<div>
<input class="InptText" type="text" id="code" name="code" maxlength="6" minlength="6" required>
</div>
<div>
<button type="button" class="SMSBut" onclick="submitPhoneNumberAuthCode()">
<h2 id="check-in-button" class="Text2"> check </h2>
</button>
</div>
</div>
</div>
My questions:
Is it secure? can the user get configuration info from the file? if so how to secure it?
Is there a way to make sure the user won't just submit the form without verifying the phone number?
Do I need to add ReCaptcha in the form page, or the one with auth will be enough?
I'm not good with JavaScript, so please any suggestions will be appreciated.
I am trying do delete employees in my mongoose database through my admin.ejs page.
So far I've tried to do with with a normal POST request and with DELETE using method-override but neither work.
// Attempt Without method-override
//Schema//
const empSchema = {
name: String,
number: String
};
const Employee = mongoose.model("Employee", empSchema);
//admin.ejs//
<form action="/deleteEmp" method="POST" >
<div>
<label>Name</label>
<input type="text" name="name">
</div>
<button class="btn btn-primary" type="submit">Delete Employee</button>
</form>
//app.js//
app.post("/deleteEmp", function(req, res) {
Employee.findOneAndDelete({name: req.params.name}, function(err, result) {
if(!err) {
console.log('User Deleted');
res.redirect("admin");
} else {
console.log(err);
}
});
});
//Attempt with method-override//
//admin.ejs//
<form method="POST" action="/deleteEmp?_method=DELETE">
<div>
<label>ID</label>
<input type="text" name="id">
</div>
<button class="btn btn-primary" type="submit">Delete Employee</button>
</form>
//app.js//
app.delete("/deleteEmp", function(req, res) {
Employee.findOneAndDelete({name: req.params.name}, function(err, result)
{
if(!err) {
console.log('User Deleted');
res.redirect("admin");
} else {
console.log(err);
}
});
});
In my attempt without method override it will go through if it is set to POST method instead of DELETE but the employee is not deleted. If the method is set to DELETE it returns a cannot GET /deleteEMP
I didn't have any success with method-override, so I wonder if I am missing something?
Although you can perform a delete operation through a POST request, it is recommended to use the proper http VERB (GET, POST, PUT, DELETE ..) for each case. So in your case i would use an AJAX delete request to delete the document.
By the way, the reason that your first option (action="/deleteEmp" method="POST") does not work is a mistake in your controller. Use name: req.body.name instead of name: req.params.name. The data you send is in the body of your request object.
"cannot GET /deleteEMP" indicates that u sent GET request. Try to send DELETE request from Postman or XMLHttpRequest(Ajax). HTML forms only support GET and POST as HTTP request methods.
app.post('/reset/:token', function(req, res) {
async.waterfall([
function(done) {
User.findOne({ 'local.resetPasswordToken' : req.params.token, 'local.resetPasswordExpires' : { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('resetMessage', req.params.token);
return res.redirect('back');
}
], function(err) {
res.redirect('/');
});
});
app.get('/reset/:token', function(req, res) {
User.findOne({ 'local.resetPasswordToken': req.params.token, 'local.resetPasswordExpires' : { $gt: Date.now() } }, function(err, user) {
if (!user) {
req.flash('forgotMessage', req.params.token );
return res.redirect('/forgot');
}
res.render('reset.ejs', { user: req.user, message: req.flash('resetMessage') });
});
});
<!--Reset.ejs page ResetPassword FORM -->
<form action="/reset/:token" method="post">
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" name="newpassword">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="text" class="form-control" name="confirmpassword">
</div>
<button type="submit" class="btn btn-warning btn-lg">Reset</button>
</form>
I able to get the token with req.params.token for the "post" after clicking
http://localhost:8080/reset/fed831abf73150c96f6a3e392b5cbdcaccdeb9bd
Later when I submit through the reset.ejs for the "get" I couldn't retrieved any token value with req.params.token.
Any solution to it?
I imagine that the original code for this might have come from http://sahatyalkabov.com/how-to-implement-password-reset-in-nodejs/. In this tut the jade templating engine is used and if you look at the reset.jade you will see that it starts with
form(method='POST')
but no action is defined. I don't really know jade but in your example you are using ejs and in your code you are setting the action to
form action="/reset/:token" method="post"
and as everybody has pointed out the route that you post to is exactly /reset/:token. So req.params will be :token and the reset will fail. What you need to do is post the url exactly as it appears in the get request. If you read
Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")
you can see that you can amend your reset.ejs page code to read
form action="" method="post"
Now the post should have an action equal to the get url with the token in place and the reset should occur.
you need another form with method='get' and action='reset/' + tokenvar. Also your async waterfall does not call done() so will not call the redirect if the user exists