How to implement this in node.js? - javascript

I have the following request handler that would sign in a user with Firebase. Upon successful login, I'd like to redirect the user to another page.
Would I change window.location to another page within the (document).ready() javascript function? Or would I implement the change here, with a res.redirect (that I did try) but nothing happened, I just got back a status code within the console.
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
console.log('a new user has signed in! their e-mail address: ' + user.email + ' | User ID: ' + user.uid)
}).catch(function (error) {
console.log(error)
})
})
Call:
$("#sign-in").on('click', function (event) {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
data: {
email: $('#email').val(),
password: $('#password').val()
}
});
});

Like George said, if you are doing a ajax post it won't redirect.
Maybe something like this could help you:
app.post('/api/sign-in', function (req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(function (user) {
res.send({ redirect: '/profile' })
}).catch(function (error) {
console.log(error)
})})
Javascript:
$(document).ready(function () {
$('#sign-in').click(function () {
event.preventDefault()
$.ajax({
url: '/api/sign-in',
method: 'POST',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
if (typeof data.redirect === 'string') {
window.location = data.redirect;
}
}
});
});
});
Hope it can be useful.

Related

I need to send an alert back to the user when there is no records found

This is my post request from nodejs server
app.post('/api/users', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400);
console.log(req.body);
var data = req.body;
db.collection('users').findOne({
username: data.username
}, (err, result) => {
if (result === null) {
db.collection('users').insertOne(data, function (err) {
if (err) throw err;
console.log("Record inserted!");
res.status(200).send("recordInserted");
})
} else {
console.log("Already exists");
res.status(500).send("userExists");
}
})
})
This is my ajax request
$('#signupForm').on('submit', function () {
var userData = {
fullName: $("#fullName").val(),
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val()
};
$.ajax({
type: "post",
data: userData,
dataType: "text",
url: "/api/users",
function (data, status) {
if(data== 'recordInserted'){
alert("Recors inserted");
console.log("Inserted \n" + data +"\n" + status);
}
else if(data == 'userExists') {
alert("User exists");
console.log(data + "\n " + status);
}
}
});
});
I cant send back the response to the ajax request and because of that the page doesn't reload or show an error if the user already exists
As a first order of business, the preferred way for awhile now to handle responses in AJAX has been to utilize deferred objects.
let request = $.ajax({url: 'google.com', type:'get'});
request.done(function(response){
// handle response
});
Beyond that, your back-end looks to be fine.
Although!
I would highly recommend changing how you go about error handling on the server-side. If the server throws an error, the client will be left hanging until they timeout. Its best to alert the client that an error has occurred, as well.
use of e.preventDefault(); method will stop the page from being reload. you can copy paste the code
$('#signupForm').on('submit', funfunction(e) {
e.preventDefault();
let userData = {
fullName: $("#fullName").val(),
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val()
};
$.ajax({
type: "post",
data: userData,
dataType: "text",
url: "/api/users",
function (data, status) {
if(data== 'recordInserted'){
alert("Recors inserted");
console.log("Inserted \n" + data +"\n" + status);
}
else if(data == 'userExists') {
alert("User exists");
console.log(data + "\n " + status);
}
}
});
});

Node.js-Both delete and redirect operations not working from single post request using AJAX

I need to delete the rows if corresponding checkboxes are checked.I am using jquery and Ajax to send the selected checkbox ids and deleting.But redirect after delete not working, If i use redirect code in Ajax sucess function, redirecting before the delete operation is preformed.
Here is my client side code:
$(document).ready(function(){
$("#chkAll").change(function(){
var status = this.checked;
$('.chk').each(function(){
this.checked = status;
});
});
$('#sub').click(function(event){
var id=$('.chk:checked').map(function(){
return $(this).val();
}).get().join(",")
$.ajax({
type: 'POST',
data: id,
url: '/del',
timeout: 10000,
success: function (data) {
if typeof data.redirect == 'string'
window.location = data.redirect
}
});
event.preventDefault();
})
});
serverside code:
router.post('/del', function(req, res, next) {
var chh=req.body;
var newchh=JSON.stringify(chh);
chh=newchh.replace(/:|"|{|}|/g,'');
var arr=[];
arr=chh.split(",");
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('ch').remove({'id1':{'$in':arr}}, function(err, result) {
assert.equal(null, err);
console.log(' deleted');
db.close();
});
});
res.redirect('/');
});
Help me out.
You need to send response back to ajax request like this :
res.send({status: true, url: "/"});
And then in your ajax
success: function (data) {
if(data.status)
window.location = data.url
}

How to render a page from an AJAX POST request?

I make a POST AJAX request:
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
$.ajax({
// Send token to your backend via HTTPS (JWT)
url: '/auth',
type: 'POST',
data: {token: idToken},
success: function (response) {
var userID = response.userID
firebaseDB.ref('/users/' + userID)
.once('value')
.then(function(snapshot) {
$.post('/members-area/' + userID, snapshot.val(), function(data, status) {
});
});
}
});
});
My handler:
app.use('/members-area/', function(req,res,next) {
console.log(req.body) //works well and gives object
res.render('members-area', { Snapshot: req.body})
})
However, it does not render the page. Why is that and how can I achieve that?
I can't move that function call outside of the success attribute of the AJAX call, as then the decoded userID variable would not be available.

How Can I Use .find() To Find Documents in DB For Logged In User?

On the backend I have this for my 'get' request to my '/logs' collection. The data comes back as an array called "times":
router.get('/', (req, res) => {
time
.find({'userName': req.params.userName})
.exec()
.then(times => {
console.log(req.params.userName)
//console.log(times)
res.json({
times: times.map(
(time) => time)
});
})
.catch(
err => {
console.error(err);
res.status(500).json({message: 'Internal server error'});
});
});
I am trying to display times for which ever user is logged in and I can do that however the network tab still shows all times for all users instead of the user who is logged in. I have this on the front end making the request:
function getTimesFromDB(callback) {
var user = state.loggedIn;
$.ajax({
type: 'GET',
dataType: 'json',
url: '/logs',
'headers': {
"content-type": "application/json",
},
'data': {
'userName': user,
},
success: callback,
})
}
Any help would appreciated. thanks!
Are you getting the correct value in req.params.userName?
Can you try using req.query.userName instead.

req.login is not logging the user

What I am trying to do is use ajax to send a post request to the server, and make sure that post request does not refresh the page (using e.preventDefault). On the server I want to check if the username or email is taken and if it is not taken, then automatically log the user in and then refresh the page. The issue is when I call req.login and submit the data to be logged in it doesn't seem to be working but the page still refreshes. Any ideas?
app.post('/signup', function (req, res) {
var userDetails = User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password1, bcrypt.genSaltSync(10))
});
User.findOne({
$or: [{
'username': req.body.username
}, {
'email': req.body.email
}]
}, function (err, user) {
if (user) {
if (allClients.indexOf(req.body.socket)) {
if (user.username === req.body.username) {
io.to(req.body.socket).emit('userInfo', 'That username is already in use.');
} else {
}
if (user.email === req.body.email) {
io.to(req.body.socket).emit('userInfo', 'That email is already in use.');
} else {
}
} else {
console.log('timeout error 822')
}
} else {
req.login(userDetails, function (err) {
if (!err) {
userDetails.save(function (err) {
if (err) throw err;
res.redirect('/');
});
} else {
console.log(err)
}
})
}
if (err) {
return done(err);
}
});
});
Here is where I make the ajax post request. As you can see I am preventing the form submit to refresh the page, but if the form is succesful it will submit.
$("#form1").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/signup',
data: $(this).serialize(),
success: function(data)
{
window.location.reload(true);
}
});
});
I believe your 'already taken' messages are considered success by your API.
You can either throw an error on those cases and catch with $.ajax or set a different response and read data on success.

Categories