.signInWithEmailandPassword is not a function - javascript

I was following this video from the Firebase Team to add Firebase Auth to my application (https://www.youtube.com/watch?v=-OKrloDzGpU)
I have added the web application script generated for my project in Firebase into the html section of my app and basically copied the other code to do the login and signing up as seen in the code below
But I got this error which I have no idea why its triggering
TypeError: auth.signInWithEmailandPassword is not a function. (In 'auth.signInWithEmailandPassword(email, pass)', 'auth.signInWithEmailandPassword' is undefined)
HTML Code
<!DOCTYPE html> <meta charset="utf-8" />
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-auth.js"></script>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" required placeholder="Email" />
<input id="txtPassword" type="password" required placeholder="Password" />
<button id="btnLogin" class="button-is-link">Login</button>
<button id="btnSignUp" class="button-is-info">Sign Up</button>
</div>
<script src="js/auth.js"></script>
</body>
</html>
Auth.js
(function() {
// Initialize Firebase
var config = {
apiKey: 'API KEY',
authDomain: 'DOMAIN',
databaseURL: 'DATABASE',
projectId: 'ID',
storageBucket: 'BUCKET',
messagingSenderId: 'ID'
};
firebase.initializeApp(config);
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
firebase.auth().onAuthStateChange(firebaseUser => {
if (firebaseUser) {
console.log('U are logged in');
} else {
console.log('Not logged in');
}
});
});
})();

The exact method name is signInWithEmailAndPassword, with an upper case "A" at And.
It is the same with createUserWithEmailAndPassword.

run given below command, Before execute make sure to delete "package-lock.json"
npm i #angular/fire#latest --save

Related

How can i fetch data from realtime database using firebase v9?

I was wondering how can I fetch the data everytime I create a new guest through form using realtime database in firebase v9? I was trying to find the ways of doing it on the internet but I couldn't. So i want to fetch data from realtime database everytime i submit my form and show the data in a table. Also is there and easier way to send data than I did it here using set and ref? Thanks.
Here is the existing code:
HTML:
<body>
<form class="form">
<span>Guest name:</span>
<input type="text" name="name" id="name"><br>
<span>Guest surname:</span>
<input type="text" name="surname" id="surname"><br>
<span>Tel:</span>
<input type="number" name="tel" id="tel" maxlength="16"><br>
<span>Country:</span>
<input type="text" name="country" id="country"><br>
<span>Arrival date:</span>
<input type="date" name="arrivalDate" id="arrivalDate"><br>
<span>Departure date:</span>
<input type="date" name="departureDate" id="departureDate"><br><br>
<input type="submit" value="Send">
</form>
<p class="success"></p>
</body
jQuery:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
const firebaseConfig = {
apiKey: "hidden",
authDomain: "hidden",
databaseURL: "hidden",
projectId: "reservations-32294",
storageBucket: "reservations-32294.appspot.com",
messagingSenderId: "773498700596",
appId: "1:773498700596:web:618889de8423f066071b61"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const db = getDatabase();
function insertData() {
set(ref(db, "Guests/" + $("#name").val() + " " + $("#surname").val()), {
Name: $("#name").val(),
Surnam: $("#surname").val(),
Tel: $("#tel").val(),
Country: $("#country").val(),
ArrivalDate: formatDate($("#arrivalDate").val()),
DepartureDate: formatDate($("#departureDate").val())
})
.then(() => {
$(".success").html("Success!").fadeIn("fast");;
setTimeout(function() {
$('.success').fadeOut('fast');
}, 2000);
$("input").removeAttr("disabled");
})
.catch(error => alert(error));
}
$(".form").submit(function(e) {
e.preventDefault();
$("input").attr("disabled", "true");
insertData();
});
const formatDate = (date) => {
const newDate = date.split("-");
let day = newDate[2];
let month = newDate[1];
let year = newDate[0];
let newFormat = `${day}.${month}.${year}.`;
return newFormat;
}
You just need to read data with the get method and listen for changes with onValue method.
import { getDatabase, ref, set, get, onValue } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const db = getDatabase();
const guestsRef = ref(db, 'Guests');
onValue(guestsRef , (snapshot) => {
if (snapshot.exists()) {
const data = snapshot.val();
// Do something with your data.
}
});
Docs: https://firebase.google.com/docs/database/web/read-and-write#web_value_events

Error while uploading images to Cloudinary from the front-end and store the data in a MySQL database with the use Axios on Node JS

I am creating a web app with React. There's a form which users can input text data and multiple image files. I need to upload the submitted images to Cloudinary and store the Cloudinary Image URL and other text data in a MySQL database.
However there's an error. The image files don’t pass to the server. I assume that my implementation has to be changed for the image inputs but figured out how exactly. May I know a solution for this? Thank you!
Client
import { useState } from "react";
import Axios from 'axios';
function Verify() {
// Text Inputs
const [address, setAddress] = useState("")
const [name, setName] = useState("")
const [nic, setNIC] = useState("")
// Image inputs
const [nicfront, setNICFront] = useState("")
const [nicback, setNICBack] = useState("")
const [selfie, setSelfie] = useState("")
const submitApplication = () => {
console.log("start")
Axios.post('http://localhost:3001/create', {
address: address,
name: name,
nic: nic,
nicfront: nicfront,
nicback: nicback,
selfie: selfie
}).then(() => {
console.log("Success")
});
};
return (
<>
<section>
<label>Address</label>
<input type="text" onChange={(event) => { setAddress(event.target.value) }} />
<label>Full Name</label>
<input type="text" onChange={(event) => { setName(event.target.value) }} />
<label>NIC Number</label>
<input type="text" onChange={(event) => { setNIC(event.target.value) }} />
<label>NIC Front</label>
<input id="imagefront" name="imagefront" type="file" onChange={(event) => { setNICFront(event.target.value) }} />
<label>NIC Back</label>
<input id="imagefront" name="imagefront" type="file" onChange={(event) => { setNICBack(event.target.value) }} />
<label>Upload a selfie with the NIC</label>
<input id="imagefront" name="imagefront" type="file" onChange={(event) => { setSelfie(event.target.value) }} />
<div>
<div class="control">
<button onClick={submitApplication} >Submit for Review</button>
</div>
</div>
</section>
</>
);
}
export default Verify;
Server
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const cloudinary = require("cloudinary").v2;
require('dotenv').config();
const cl_user = process.env.CLUSER;
const cl_key = process.env.CLKEY;
const cl_secret = process.env.CLSECRET;
const app = express()
app.use(cors());
app.use(express.json());
// Cloudinary intergration
cloudinary.config({
cloud_name: cl_user,
api_key: cl_key,
api_secret: cl_secret
});
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'blockverify'
})
app.post('/create', (req, res) => {
var wallet = ""
var name = ""
var nic = ""
var nicfront = ""
var nicback = ""
var selfie = ""
var state = 1
// Retrieving data from the client
wallet = req.body.address
name = req.body.name
nic = req.body.nic
nicfront = req.body.nicfront
nicback = req.body.nicback
selfie = req.body.selfie
cloudinary.uploader.upload(nicfront.tempFilePath, function (err, result) {
console.log("Error: ", err);
console.log("Result: ", result);
var frontURL = result.secure_url;
});
cloudinary.uploader.upload(nicback.tempFilePath, function (err, result) {
console.log("Error: ", err);
console.log("Result: ", result);
var backURL = result.secure_url;
});
cloudinary.uploader.upload(selfie.tempFilePath, function (err, result) {
console.log("Error: ", err);
console.log("Result: ", result);
var selfieURL = result.secure_url;
});
db.query("INSERT INTO applications (wallet, name, nic, nicfront, nicback, selfie, state) VALUE (?,?,?,?,?,?,?)", [wallet, name, nic, nicfurl, nicback, selfie, state], (err, result) => {
if (err) {
console.log(err)
} else {
res.send("Inserted!")
}
})
})
app.listen(3001, () => {
db.connect(function (err) {
if (err) throw err;
console.log("Connected to MySQL!");
});
});
Following is the error.
Error: {
message: 'Missing required parameter - file',
name: 'Error',
http_code: 400
}
Result: undefined
/Users/sandaru/DATA DRIVE/Degree/L6/FYP/Project/block-verify/server/index.js:50
var frontURL = result.secure_url;
^
TypeError: Cannot read properties of undefined (reading 'secure_url')
at /Users/sandaru/DATA DRIVE/Degree/L6/FYP/Project/block-verify/server/index.js:50:31
at /Users/sandaru/DATA DRIVE/Degree/L6/FYP/Project/block-verify/server/node_modules/cloudinary/lib/utils/index.js:1259:14
at IncomingMessage.<anonymous> (/Users/sandaru/DATA DRIVE/Degree/L6/FYP/Project/block-verify/server/node_modules/cloudinary/lib/uploader.js:507:9)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Hey there it looks like you might be having issues with your file.
Options for a file to upload. It can be:
a local file path (supported in SDKs only)
the actual data (byte array buffer). For example, in some SDKs, this
could be an IO input stream of the data (e.g., File.open(file,
"rb")).
the Data URI (Base64 encoded), max ~60 MB (62,910,000 chars)
the remote FTP, HTTP or HTTPS URL address of an existing file
a private storage bucket (S3 or Google Storage) URL of a whitelisted
bucket
Look at some examples,
https://cloudinary.com/documentation/upload_images#file_source_options

Onclick is not defined - EventListener null

The problem is that the onlclick returns "main.html:1 Uncaught ReferenceError: removePost is not defined at HTMLButtonElement.onclick (main.html:1)" I need to load the function removePost to erase the post with the specific id. After that I tried the same trick but with the eventListener (see in the final of the code) but returns null, the html reference it seems to be out of scope. Uncaught TypeError: Cannot read property 'addEventListener' of null at main.js:70.
Any ideas? thx in advance.
HTML
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
rel="stylesheet"
/>
<link rel="stylesheet" href="style.css" />
<title>Count Likes</title>
</head>
<body>
<div class="root"></div>
<div class="CountLike" id="Like Count">
<button class="button button1">
<i class="fa fa-heart"></i> Like <span class="counterStat">...</span>
</button>
</div>
<div class="formContainer">
<input id="nameInput" type="text" placeholder="Escribe tu nombre" />
<input id="bodyInput" type="text" placeholder="Ingresa comentario" />
<button id="btnSend">Publicar</button>
</div>
<table class="table">
<tbody id="table"></tbody>
</table>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.9.1/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyBoHBd8UGJ2oFxyEu9lqbIWmg_j-MvcYZQ",
authDomain: "like-button-2203f.firebaseapp.com",
databaseURL: "https://like-button-2203f-default-rtdb.firebaseio.com",
projectId: "like-button-2203f",
storageBucket: "like-button-2203f.appspot.com",
messagingSenderId: "949206080621",
appId: "1:949206080621:web:8b2146c19e8c082b913364",
measurementId: "G-REJZ56MGNY",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// firebase.analytics();
</script>
<script type="module" src="main.js"></script>
</body>
</html>
JAVASCRIPT
const db = firebase.firestore();
const dCounters = document.querySelectorAll(".CountLike");
[].forEach.call(dCounters, function (dCounter) {
const el = dCounter.querySelector("button");
const cId = dCounter.id;
const dDatabase = firebase.database().ref("Like Number Counter").child(cId);
// get firebase data
dDatabase.on("value", function (snap) {
const data = snap.val() || 0;
dCounter.querySelector("span").innerHTML = data;
});
// set firebase data
el.addEventListener("click", function () {
dDatabase.transaction(function (dCount) {
return (dCount || 0) + 1;
});
});
});
document.getElementById("btnSend").addEventListener("click", () => {
let name = document.getElementById("nameInput").value;
let body = document.getElementById("bodyInput").value;
db.collection("post")
.add({
name: name,
body: body,
})
.then(function (docRef) {
console.log("id ", docRef.id);
document.getElementById("nameInput").value = "";
document.getElementById("bodyInput").value = "";
})
.catch(function (error) {
console.error("Error ", error);
});
});
const table = document.getElementById("table");
db.collection("post").onSnapshot((querySnapshot) => {
table.innerHTML = "";
querySnapshot.forEach((doc) => {
// console.log(`${doc.id}=>${doc.data().name}`);
table.innerHTML += `
<tr>
<th scope='row'>${doc.id}</th>
<td>${doc.data().name}</td>
<td>${doc.data().body}</td>
<td><button onclick="removePost('${doc.id}')"
id="btnRemove" class="far fa-trash-alt"></button></td>
<td><button id="editPost" class="far fa-edit"></button></td>
</tr>`;
});
});
function removePost(id) {
db.collection("post")
.doc(id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
}
EventListener
document.getElementById("btnRemove").addEventListener("click", (evt) => {
db.collection("post")
.doc(evt.target.doc.id)
.delete()
.then(function () {
console.log("Removed");
})
.catch(function (error) {
console.error("Error - " + error);
});
});

How to call javascript function defined in another file from HTML?

I am trying to write a website, but when I try to call a JavaScript function defined in another file from my HTML code I get the following error
Uncaught ReferenceError: fetchConfs is not defined at admin.html:46
I did import the script in the <head> portion of the HTML, but for some reason, I am still getting the error.
admin.html:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="bundle.css">
<script type="text/javascript" src="bundle.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-firestore.js"></script>
<title>Dilo+</title>
</head>
<header class="header">
<img src="logo.png">
<p>Sobreviviendo a lo imposible</p>
</header>
<body>
<script type="text/javascript">
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
initApp = function () {
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
var email = user.email;
user.getIdToken().then(function (accessToken) {
document.getElementById("greeter").textContent = "Hola " + email;
});
} else {
window.location.href = '/login.html'
}
}, function (error) {
console.log(error);
});
};
window.addEventListener('load', function () {
initApp()
document.getElementById("logout").onclick = function logout() {
firebase.auth().signOut().then(function () { window.location.href = '/login.html' });
}
var confs = fetchConfs();
});
</script>
<h1 id="greeter">Error, inicia sesión para continuar</h1>
<button class="mdc-button foo-button" id="logout" style="float: right;">
Cerrar Sesión
</button>
</body>
</html>
app.js (This file is compiled to bundle.js using webpacks before deploying):
import {MDCRipple} from '#material/ripple/index';
import { MDCTextField } from '#material/textfield';
import * as firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/firebase-auth';
const ripple = new MDCRipple(document.querySelector('.foo-button'));
var firebaseConfig = {
apiKey: "",
authDomain: "dilo-mas.firebaseapp.com",
databaseURL: "https://dilo-mas.firebaseio.com",
projectId: "dilo-mas",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(firebaseConfig);
document.getElementById("tbut").onclick = function submitForm() {
var date = Date.now().toString()
var x = document.getElementById("conf").value;
firebase.firestore().collection("confesiones").doc(date).set({
conf: x
})
.then(function () {
console.log("Document successfully written!");
var y = document.getElementById("conf").value;
console.log("input " + x)
alert("Exito");
})
.catch(function (error) {
console.error("Error writing document: ", error);
alert("Error envíando tu confesión")
});
document.getElementById("conf").reset();
}
function fetchConfs() {
var confs = db.collection("confesiones").where(firebase.firestore.FieldPath.documentId(), "!=", "root").get();
return confs;
}
I already tried assigning fetchConfs() to the window object or to a global variable, but I'm still getting the same error.
Note: I am using webpacks and other npm plugins to compile js and sass code to static files for deployment.
Scripts are run in the order that they are listed in <head>, then any in the body. If the function is in a script listed later, that function may not be defined yet when it is run.
To fix this, define fetchConfs earlier on.

Login button does not work for firebase auth

I'm a newbie at firebase.
I'm trying to code a simple login page where the user logs in and then is redirected to home.html.
This is my index page:
<html>
<body>
<script src="https://gstatic.com/firebasejs/live/3.1/firebase.js"></script>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action">Log in</button>
<button id="btnSignUp" class="btn btn-secondary">Sign Up</button>
<button id="btnLogout" class="btn btn-action hide">Log out</button>
</div>
<script src="app.js"></script>
</body>
</html>
And this is my app.js:
(function() {
// Initialize Firebase
const config = {
apiKey: "...",
authDomain: "fir-test-bb3bd.firebaseapp.com",
databaseURL: "https://fir-test-bb3bd.firebaseio.com",
projectId: "fir-test-bb3bd",
storageBucket: "fir-test-bb3bd.appspot.com",
messagingSenderId: "509522467811"
};
firebase.initializeApp(config);
// Get elements
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
const btnLogout = document.getElementById('btnLogout');
// Add login event
btnLogin.addEventListener('click', e => {
// Get email and pass
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
// Handle Account Status
firebase.auth().onAuthStateChanged(user => {
if (user) {
window.location = 'home.html'; //After successful login, user will be redirected to home.html
// Add signup event
btnSignUp.addEventListener('click', e => {
// Get email and pass
// TODO: CHECK FOR REAL EMAIL
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
// Sign in
const promise = auth.CreateUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
// Add a realtime listener
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser);
} else {
console.log('not logged in');
}
});
}
});
});
When i go enter a valid username and password nothing happens, when I enter an invalid username and password nothing happens. When I check the console logs there is absolutely nothing even though it should be stating what is happening.
Any idea?
Thank you again for any help.
UPDATE 1
This is the new login bit...still same problem
//Add login event
btnLogin.addEventListener('click', e => {
//Get email and pass
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
{
promise.then(onResolve, onReject)
onResolve(e => console.log(e.message));
firebase.auth().onAuthStateChanged(user => {
if(user) }{
window.location = 'home.html';
}});

Categories

Resources