I have the following code that would execute, but on a button click that calls function 'Auth', I get an error that it is not defined. Why is that? I did define it in the below code, did I not?
app.get('/sign-in', function(req, res, next) {
res.render('sign-in', {
title: 'Sign In'
})
function Auth(event) {
event.preventDefault()
firebaseAuth.signInWithEmailAndPassword('email@email.com', 'password').catch(function(error) {
var errorCode = error.code
var errorMessage = error.message
console.log(errorCode)
console.log(errorMessage)
})
}
})
It's called here (pug):
h2 Please sign in
form(class='form-signin' role='form')
input#email.form-control(type='email' placeholder='E-mail address' required='' autofocus='')
input#password.form-control(type='password' placeholder='Password' required='')
button.btn.btn-lg.btn-primary.btn-block(type='submit' onclick='Auth(event)') Sign In
EDITED:
(pug file)
link(rel='script', href='../public/javascripts/scripts.js')
body
.container
h2 Please sign in
form(class='form-signin' role='form')
input#email.form-control(type='email' placeholder='E-mail address' required='' autofocus='')
input#password.form-control(type='password' placeholder='Password' required='')
button.btn.btn-lg.btn-primary.btn-block(type='submit') Sign In
(public/javascripts/scripts.js)
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
url: '/api/sign-in',
method: 'POST',
data: {
email: $('#email').val(),
password: $('#password').val()
}
});
}
(app.js)
function Auth(email, password) {
return firebaseAuth.signInWithEmailAndPassword(email, password)
}
app.get('sign-in', function(req,res,next) {
res.render('sign-in', { title: 'Sign In' })
})
app.get('/api/sign-in', function(req, res, next) {
Auth(req.body.email, req.body.password)
.then(function() {
console.log('success!')
})
.catch(function(error) {
console.log(error)
})
})
Here is the problem, the functions you define on your express server won't work on the client, that's now how it works.
e.g.
express code:
app.post('/api/sign-in', function(req, res, next) {
firebase.auth().signInWithEmailAndPassword(req.query.username, req.query.password)
.catch(function(error) {
console.log(error);
});
});
client code (using jQuery for clarity):
$('#button').on('click', function(event) {
event.preventDefault();
$.ajax({
url: '/api/sign-in',
method: 'POST',
data: {
username: $('#user').val(),
password: $('#pass').val()
}
});
}