Write to Firebase Storage with JavaScript gives "Cross-Origin Request Blocked" - javascript

I have made a web app which includes a form with two fields and what I want to happen is when I click the button, my data should be written to Firebase. So I made an onclick function which writes to Firebase, the function is called but it doesn't write to Firebase. I get this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
https://firebasestorage.googleapis.com/v0/b/storymap-da000.appspot.com/o?name=11-2-2018-0-6-27.
(Reason: CORS request did not succeed).[Learn More]
My vanilla JavaScript code:
var config = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX"
};
firebase.initializeApp(config);
window.addEventListener('load', function() {
const fileButton = document.getElementById("fileButton");
const up = document.getElementById("up")
});
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = firebase.storage().ref(image_name);
storageRef.put(file)
});
up.onclick=function(){
var lat = new URL(location.href).searchParams.get("lat")
var lng = new URL(location.href).searchParams.get("lng")
var title = document.getElementById("title").value
var story = document.getElementById("story").value
var database = firebase.firestore()
database.collection("Stories").add({
title:title,
story:story,
lat: lat,
lng:lng,
url:image_name});}
Any ideas?

i think you need to register your domain in your firebase app

Related

Firebase realtime database not returning any data

I am trying to retrieve an object the i added to my firebase realtime database But i am not getting anything and i dont know why . i made sure to implement and call firebase correctly .
This is the response i get one i cal the database .
and this is my imlimentation
<script>
var firebaseConfig = {
apiKey: "*",
authDomain: "*",
databaseURL: "*",
projectId: "*",
storageBucket: "*",
messagingSenderId: "*",
appId: "*"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var dbRef = firebase.database();
var contactsRef = dbRef.ref("survey");
console.log(contactsRef)
</script>
You need to attach a listener to retrieve the data:
var dbRef = firebase.database();
var contactsRef = dbRef.ref("survey");
contactsRef.once('value').then(function(snapshot) {
console.log(snapshot.val());
});
snapshot.val() will give you all the data under node survey.
For more information check this:
https://firebase.google.com/docs/database/web/read-and-write#read_data_once

I keep getting the error firebase.database is not a function

I'm trying to link my contact form in a portfolio website to firebase and keep getting (firebase.database is not a function) in my console
This is for the web, using pure javascript
var firebaseConfig = {
apiKey: "AIzaSyCzX3r8CFw84WSBuCSXR1fWM_hDrwtGMSs",
authDomain: "portfolio-4c243.firebaseapp.com",
databaseURL: "https://portfolio-4c243.firebaseio.com",
projectId: "portfolio-4c243",
storageBucket: "",
messagingSenderId: "745737502175",
appId: "1:745737502175:web:a26e5b0baa3769c9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var messagesRef = firebase.database().ref('messages');
document.getElementById('contactForm').addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
var name = getInputVal('name');
var email = getInputVal('email');
var message = getInputVal('message');
saveMessage(name, email, message);
}
// Function get value
function getInputVal(id) {
return document.getElementById(id).value;
}
//Save
function saveMessage(name, email, message) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
email: email,
message: message
})
}
This error is very common and arises because either you have not configured your config object correctly or the script tag required for using that particular functionality is missing.
In your case the config object looks fine so you have to add this script in your page
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-database.js"></script>
But please note that this script is to be added only after the core script for firebase app
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js"></script>
and for future if you want to use any other service from Firebase like Firestore or so, just make sure you have that particular script tag in there (with the config object correctly setted up).

create users on firebase using its authenticate methods

i tried sending the credentials and this error appears.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=*******. (Reason: CORS request did not succeed).
(function () {
var config = {
apiKey: "*******",
authDomain: "*******",
databaseURL: "*******",
projectId: "*******",
storageBucket: "*******",
messagingSenderId: "*******"
};
firebase.initializeApp(config);
const email = document.getElementById('email');
const password = document.getElementById('password');
const btnSignUp = document.getElementById('btnSignUp');
btnSignUp.addEventListener('click', e => {
const mail = email.value;
const pass = password.value;
firebase.auth().createUserWithEmailAndPassword(mail, pass).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
});
}());
How do I solve the CORS request blocked?
Your firebase imports are wrong, use this:
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.1.0/firebase-auth.js"></script>

Firebase data retrieval to web

// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
ref msgs clllection
var msgRef = firebase.database().ref('survey');
I am trying to connect to firebase, but I continue getting these errors on chrome console failing to connect to firebase:
Chrome console error
This is because you did not write:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
in the <head>...</head>
You have to write it to be able to use the firebase sdk in your project.
more info here:
https://firebase.google.com/docs/web/setup

Firebase Real-time Database connection from Java -> JavaScript

I want to set up a Firebase Real-time Database connection from my Java backend to my JavaScript frontend, but the messages are not pushed to the client.
The backend Java code looks like this:
FirebaseOptions options = new FirebaseOptions.Builder()
.setServiceAccount(getServletContext().getResourceAsStream("/WEB-INF/xxx.json"))
.setDatabaseUrl("https://xxx.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
DatabaseReference ref = FirebaseDatabase
.getInstance()
.getReference();
ref.child("users").setValue("aaa");
My javascript code on the frontend looks like this:
var config = {
apiKey: "xxx",
authDomain: "xxx.firebaseapp.com",
databaseURL: "https://xxx.firebaseio.com",
storageBucket: "xxx",
messagingSenderId: "xxx"
};
firebase.initializeApp(config);
var database = firebase.database();
var myRef = firebase.database().ref("users");
myRef.on('value', function(snapshot) {
alert(5);
});
Is there something wrong with this code or why are the messages are not pushed? Am I missing something?

Categories

Resources