ReferenceError while configuring Firebase Realtime database

I am trying to setup a Firebase Realtime database for my Flask application. I’m using a browser environment without a build step. My frontend is an .html file with some JS for managing sockets and hopefully, database interactions.

The below code produces the error: “ReferenceError: Can’t find variable: ref”. Does anything seem off with how I have the database configured? I’m finding the documentation to be a bit confusing for non-npm uses.

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
  import { getDatabase, ref, onValue } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-database.js";

  const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };

  const app = initializeApp(firebaseConfig);
  const database = getDatabase(app);

  const socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

    function loadChatHistory(user_id) {
        const chatRef = ref(database, 'users/' + user_id + '/chats');
        onValue(chatRef, (snapshot) => {
            const chatHistory = snapshot.val();

Running “node” on /dist folder file errors because it sees /migrations and /src folders as well

I have a node project written in typescript that I compile with tsc. It compiles to a /dist folder and then I run the output json with the command node dist/startup/server.js. My folder structure is as follows:

/node_modules
    ...
/src
    /foo
        a.ts
        b.ts
    /startup
        server.ts
/migrations
    1.ts
    2.ts
    ...

/dist (directory is created after tsc command completes)
    /foo
        ...
    /startup
        server.js

The problem is when I run node dist/startup/server.js (which should be “standalone” with node_modules) I get the error:

.../src/db/entities/appUser.ts:1
import { Entity, PrimaryColumn, Column, Index } from 'typeorm';
^^^^^^

SyntaxError: Cannot use import statement outside a module

I found that the error only occurs if I have the ./src and ./migrations directories. If I delete them, the server runs correctly.

I also tried to run the app from WITHIN the /dist folder, but that gives me another error so I believe that it means that the build expects to be run from root and not /dist (even if I copy node_modules into dist):

EntityMetadataNotFoundError: No metadata for "Tenant" was found.

Does anyone know how to make node not pick up the src and migrations folders? Or to configure tsc to be able to run within dist?

I expect that running node on a file in the /dist folder only reads the files necessary for that program to run in that directory, and not sibling directories /src /migrations.

I also expect to be able to run the code the same if I am in root or in /dist, but I believe that is a tsc issue.

How do I resolve a CORS error for google cloud functions in the browser?

I have a simple cloud function in google cloud that receives data, and submits back a response after processing the data. I kept running into a CORS error, so tried with a simple Hello World as well.

Here’s client side code (obviously changed for privacy:

callCloudFunc();
function callCloudFunc(data) {
  const url = 'https://{googe-location}.cloudfunctions.net/myCloudFunc';


  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${authToken}`
    },
    body: JSON.stringify(data),
    mode: 'cors'
  })
  .then(response => response.json())
  .then(data => {
    console.log('Success:',data);
  })
  .catch((error) => {
    console.error('Error:',error);
  });
}

Here’s server side code in the google cloud func:

import functions_framework
import itertools
from collections import Counter
from flask import escape
import json
@functions_framework.http
def myCloudFunc(request):
    if request.method == "OPTIONS":
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST",
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Max-Age": "3600",
        }

        return ("", 204, headers)

    # Set CORS headers for the main request
    headers = {"Access-Control-Allow-Origin": "*"}
    try:
        //some logic here... 
        return json.dumps(result), 200, headers
    except json.JSONDecodeError:
        return 'Invalid JSON format', 400, headers

I keep getting the following error in the browser:
Access to fetch at 'https://{google-location}.cloudfunctions.net/myCloudFunc' from origin 'https://console.cloud.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

You can replace ‘https://console.cloud.google.com’ with whatever site, doesn’t seem to work anywhere.

I tried the same call in postman and curl, and it works fine, even if I copy and paste the request in browser as curl and run in terminal or postman. It just doesn’t work in browser.

I also tired specifying a site, instead of the wildcard… so “Access-Control-Allow-Origin”: “mySite”… still doesn’t work in browser. Am I doing something wrong on the server or client side?

I ran in no-cors mode, still no luck.

Why is Safari refusing to update my site’s JS/images?

I am the creator of a webcomic powered by the Rarebit template. The Rarebit template uses Javascript calls in the “index” and “archive” to control page number, image, alt text, author notes, total number of pages, etc. I add a new page to my webcomic twice per week; after my first update, I discovered that I needed to change each JS file name every time I updated, i.e., from comic_settings1.js to comic_settings2.js. Otherwise, the browser would just return the cached version of the page instead of the new image and content. This has worked perfectly in all browsers except Safari.

When I try and view the index (following a page update) in Safari, I see the old version of the page, unless I clear cache and cookies. Sometimes I see the new html, like author notes and page number (controlled through comic_settings.js), but the image is missing. I don’t know if it would be relevant, but my steps for each update are:

  1. Upload images/pages/pgx, where “x” is the number of the latest page
  2. Upload comic_settingsx.js, comic_showx.js, and comic_archivex.js, where “x” is the new version number/letter
  3. Delete the old versions of the JS files
  4. Change the script calls in “index.html” and “archive.html” so they link to the correct JS versions, i.e.
<script src="js/comic_settingsx.js" defer></script>
<script src="js/comic_showx.js" defer></script>

I understand the problem with caching old JS files under the same name as new ones; what I don’t understand is why Safari would be using old files when I’m making sure to differentiate each updated version.

Here is a link to my webcomic, for reference: https://www.eldernetcomic.com

Why the max size of localStorage can be different on a same browser?

I write a script to test the max size of localStorage in my current browser (Chrome) with ReactJS, but it seems that the max size is not determined by the size in bytes, but the number of items in localStorage.

With the following code, the console will print 5242000 which is about 5MB:

// run on Chrome
let i = 0;
try {
    for (i = 5000000; i <= 6000000; i+=1000) {
        localStorage.setItem('test', new Array(i+1).join('a'));
    }
} catch (e) {
    console.error(i-1000);
    console.error(localStorage.getItem('test').length);
    console.error(localStorage.getItem('test'));
    localStorage.clear();
}

enter image description here

But if you change the code to:

// same ...
for (i = 5000000; i <= 6000000; i+=1000) {
        localStorage.setItem('test', new Array(i+1).join('汉'));
    }
// same code ...

enter image description here

The console will still print 5242000, which means it’s about 15MB in size. Because each Chinese character (‘汉’) takes 3 bytes in utf-8, or in utf-16 it takes more than 1 byte(I don’t remember).

Is there anything wrong with my code? Or I misunderstand something?

How to handle race condition when updating state and also changing route in ReactJS?

So I have a chat app where I can access different chat rooms. When I’m in one of the chat rooms, I can change chat rooms by clicking on the other chat rooms (just like how WhatsApp and other chat apps behaves). So I have a function which handles clicking on the other chat room as such:

const handleChatClick = () => {
   closeAllDocks(dispatch);
   history.push(`/chats/${chat.id}`);
};

So in my app, I have something called “Docks”. For example, I can open the chat room profile page, and it’ll be opened as a “Dock” on the right side (split screen). So when I want to change chat room, I want to make sure that all of these docks are closed. This is where the closeAllDocks(dispatch) function comes in. In this case, dispatch is basically const dispatch = useDispatch() from redux. So when this gets called, all the docks’ state will be set to false.

However, the issue is that, when I run this function, the history.push(...) will get executed, and the closeAllDocks(dispatch) as well, but I guess history.push(...) will finish executing first. This causes some sort of delay, where I can see the content of the dock gets changed according to the new chat room (even though it’s only for a split second) then closes.

How should I be handling this?

How do you print out data from a Firebase database and append it to HTML using jQuery?

So I’m trying to create a jQuery script to print out values on my Firebase database. Here is the database code:

firebase.initialize({
    projectName: "vibetune"
});

var database = firebase.database();

var vibes = {
    Upbeat:{
        tunings:["E Standard", "E Flat Standard", "Drop D"],
        tuningSongs:["Everlong", "My Generation", "Jailhouse Rock"]
    },
    Sad:{
        tunings:["Drop D Flat", "DADGAD","DAEAC#E"],
        tuningSongs:["Micheline", "Lost in Hollywood", "Emo Song"]
    },
    Mellow:{
        tunings:["CGCGCD", "FACGCE", "Open G"],
        tuningSongs:["An Island", "Never Meant", "Daughter"]
    },
    Heavy:{
        tunings:["D Standard", "Drop C", "AGCFAD"],
        tuningSongs:["Blood and Thunder", "Monster", "Alpha"]
    },
    Experimental:{
        tunings:["Ostritch Tuning", "Open C", "Nick Drake Tuning"],
        tuningSongs:["Venus in Furs", "Moon Song", "Pink Moon"]
    }
};

for(var vibe in vibes){
    database.ref(vibe).set({
        tunings:vibes[vibe].tunings,
        tuningSongs:vibes[vibe].tuningSongs
    })
}

What I’m trying to do is take the strings in the arrays of the tunings and tuningSongs key onto

  • tags (i.e. make each value in the array an
  • tag in a ).
    <!DOCTYPE html>
    <html>
        <head>
            <title>Vibe Tune</title>
            <link rel="stylesheet" type="text/css" href="style.css">
            <style>@import url('https://fonts.googleapis.com/css2?family=Oswald:[email protected]&display=swap')</style>
            <script src="https://static.codehs.com/cdn/latest/chsfirebase/chsfirebase.min.js"></script>
            <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        </head>
        <body>
           <img class="pgimg" alt="upbeat" src="https://lh3.googleusercontent.com/drive-viewer/AEYmBYSy_Rh7voLgctZUSBK5N3plPbZ9NWRHK4kozjAZEsAoeWZ_7zkDXtHQZIOHHbRsdQJ-DZszI_ccNCqhODnDx__wPql5pQ=s2560?source=screenshot.guru">
           <h1 class="pgtitle">Upbeat Tunings</h1>
           <h3 class="pgsub">Tunings for a happy vibe</h3>
           
           <div id="upbeat">
               <h3>Tunings</h3>
               <ul id="tunings">
                   
               </ul>
               
               <h3>Songs for Tunings</h3>
               <ul id="songsfortunings">
                   
               </ul>
           </div>
           
           <h4><a href="index.html"><i>Back to Home</i></a></h4>
           
           <script>
                $(document).ready(function(){
                   firebase.initialize({
                        projectName: 'vibetune'
                   });
                                  
                    //function updateUpbeatData(){
                        var database = firebase.database();
                        var upRef = database.ref("Upbeat");
                        
                        console.log("attemping to fetch data...");
                        
                        upRef.on("value", function(snapshot){
                            console.log("Snapshot: ", snapshot.val());
                            var nodeData = snapshot.val();
                            
                            if(nodeData != null){
                                console.log("Node data exists: ", nodeData);
                                $("#tunings").empty();
                                $("#songsfortuning").empty();
                            
                                if(nodeData.tunings){
                                    nodeData.tunings.forEach(function(tuning){
                                        $("#tunings").append("<li>" + tuning + "</li>");
                                    });
                                }
                                if (nodeData.tuningSongs){
                                    nodeData.tuningSongs.forEach(function(song){
                                        $("#songsfortunings").append("<li>" + song + "</li>");
                                    });
                                }
                            }
                            else{
                                console.log("No data found at the specified reference.");
                            } 
                        });
                    //}
                   //updateUpbeatData();
                });
           </script>
           <script src="scripts.js"></script>
        </body>
    </html>
    

    Here’s my HTML (sorry if it’s a bit messy, that was a result of my trying desperately to fix it). You can also see the tags I’m trying to fill. What am I doing wrong here? Pls help. I don’t know where else to turn 🙁

  • How can I get p5.js to work in an IIFE without using instance mode?

    I am trying to use p5.js in an IIFE. So far, when I try and use the print() method, it works as expected and logs whatever I pass to it in the console log. Here’s my code below.

    (function () {
        function setup() {
            print("Hello World");
        }
    
        $(document).ready(function () {
            new p5();
            setup();
        });
    })();
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8" />
            <meta
                name="viewport"
                content="width=device-width, initial-scale=1.0"
            />
            <script
                src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
                integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
                crossorigin="anonymous"
                referrerpolicy="no-referrer"
            ></script>
            <script
                src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.min.js"
                integrity="sha512-uaz5GpnQoE6t5echKlX8P52czvsIGgLPcvlzfvRubLZ1Hp8JemUDnbUiAahbVtPb+jUVrNETuXvAhDDF/N3M4w=="
                crossorigin="anonymous"
                referrerpolicy="no-referrer"
            ></script>
            <title>Game</title>
        </head>
        <body>
            <main>
                <div id="puzzle-container">
                    <canvas id="puzzle"></canvas>
                </div>
            </main>
    
            <script src="main.js"></script>
        </body>
    </html>

    I can even use the select() method to target an element in the DOM and print it out and it also works. However, when I try to use the createCanvas() function it doesn’t seem to work. A default canvas will be generated but it won’t have the specified size, or be placed in a specified parent container using the parent() method. I get no errors either, only a warning with this message: “p5.js seems to have been imported multiple times. Please remove the duplicate import.”

    Is what I’m looking to do possible?

    How can I write a JavaScript function with lots of optional arguments concisely and legibly? [closed]

    I’m writing NodeJS middleware at the moment, and I frequently end up with functions that have tons of arguments.

    Most of these have default values, and there’s nothing wrong with the way they are at the moment, except it’s confusing to read.

    const getItems = (itemsPerPage = 250, filters = [], tags = [], sinceDate, untilDate) => {
      // we'd probably make an API call here
      return items;
    };
    

    I am also trying out a new paradigm where most of the arguments are passed in a single object, then joined to an object of default values within the function. This is nice, but it does have that internal bulk that I don’t like either.

    const getItems = (options = {}) => {
      const defaultOptions = {
        itemsPerPage: 250,
        filters: [],
        tags: [],
      };
      
      options = {
        ...defaultOptions,
        ...options,
      };
      
      // we'd probably make an API call here
      return items;
    };
    

    I made a Codepen to show what I mean: https://codepen.io/gorgonfreeman/pen/poYEmOQ

    As far as I know, these are the only two paradigms out there, but I’d like to know – does anyone have a neater/better way to do this? Even a variation that tidies up one or the other.

    I’ve tried writing functions with a lot of optional parameters, and with an object of parameters, and will likely end up with a mix. Something like all the optional parameters related to search > options object, and other parameters as arguments. I like the options object approach so far – except that it’s top-heavy.

    HttpOnly won’t set on true [duplicate]

    the cookie is set perfectly on the client-side when i comment the last three lines, my major problem is with the httpOnly it wouldn’t be set to true.
    this is my React code :

      withCredentials: true,
      headers: {
        "Content-Type": "application/json",
      },
    });
    
    const data = response.data;
    const accessToken = data.access_token;
    const refreshToken = data.refresh_token;
    
    cookies.set('access_token', accessToken, {
      expires: 7,
      path: '/',
      httpOnly: true,
      secure: true,
      sameSite: "None"
    });
    

    Springboot:

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000") // Allow requests from this origin
                    .allowedMethods("GET", "POST", "PUT", "DELETE")
                    .allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
                    .exposedHeaders(HttpHeaders.SET_COOKIE) 
                    .allowCredentials(true);
        }
    }
    
    

    i tried to let the httpOnly field on true without commenting it but in that case the cookie won’t even be set on the browser.

    Api request returning cors [duplicate]

    I’m new to Api’s so trying to get a feel for how they work. I wrote this code in Javascript but it’s returning an error.

    function loadFootballData() {
      fetch("https://api.football-data.org/v4/competitions/CL/matches", {
        method: "GET",
        headers: {
          "X-Auth-Token": "my api key",
          "Access-Control-Allow-Origin": "*",
        },
      })
        .then((response) => response.json())
        .then((data) => console.log(data));
    }
    

    The error:

    Access to fetch at ‘https://api.football-data.org/v4/competitions/CL/matches’ from origin ‘http://127.0.0.1:5501’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘http://localhost’ that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

    What am I missing?

    I added ‘Access-Control-Allow-Origin’:’*’, which i thought would mean the api request can have any origin (including my localhost) but it didn’t work. What am I fundamentally not understanding about how APIs work?

    Create a playlist using Spotify API [duplicate]

    I am using the API of spotify following the documentation given at developer.spotify.com. I can get a token and search artists, tracks, etc.
    I use a simple html page and a single JS file.

    const getToken = async () => {
      const result = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
          'Content-Type' : 'application/x-www-form-urlencoded',
          'Authorization' : 'Basic ' + btoa(clientId + ':' + clientSecret)
        },
        body: 'grant_type=client_credentials'
      })
      const data = await result.json()
      token = data.access_token
      console.log(token)
    }
    

    But it seems impossible to get a token that allows me to access actions specific to my account, such as creating a playlist.

    const getSuperToken = async () => {
      const codeVerifier = generateRandomString(64)
      const hashed = await sha256(codeVerifier)
      const codeChallenge = base64encode(hashed);
      
      const redirectUri = "http://localhost:63342"
      const scope = "playlist-modify-public playlist-modify-private"
      const result = await fetch(
        "https://accounts.spotify.com/authorize" +
        "?response_type=code" +
        "&client_id=" + encodeURI(clientId) +
        "&scope=" + encodeURI(scope) +
        "&code_challenge_method=S256" +
        "&code_challenge=" + encodeURI(codeChallenge) +
        "&redirect_uri=" + encodeURI(redirectUri))
      console.log(await result.json())
    

    I get the error :

    Access to fetch at ‘https://accounts.spotify.com/authorization?client_id=591b….d247&scopes=playlist-modify-private&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F63342’ from origin ‘http://localhost:63342’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

    The documentation doesn’t mention a such issue, and I didn’t find any solution on other topics on stackoverflow or spotify or other sites. The only things that seem to work are old codes that don’t work anymore (since an update of spotify I guess).
    So has anyone successfully used one of these scopes recently (less than 2 years maybe)?

    PS: I’m french sorry if I made language mistakes

    Adding return type on a function TypeScript [duplicate]

    I am trying to declare the type of return data in a function. Here’s the function:

    export const getCurrentUserData = async (): User => {
        const value = await storage.getItem('currentSite');
        if (value === null) {
            return '';
        } else {
            const getuserData = JSON.parse(value)
            const userData = {
                email: getuserData.userData.email,
                id: getuserData.userData.id,
                name: getuserData.userData.name,
                userKey: getuserData.userData.userKey,
                userRole: getuserData.userData.userRole,
                photo: getuserData.userData.photo,
            }
            return userData;
        }
    }

    Here’s my data type:

    export type User = {
        email: string,
        id: string,
        name: string,
        userKey: string,
        userRole: string,
        photo: string,
    }

    Am i doing these the right way? Because it shows the error: 'Type 'User' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor '

    How do I “preventDefault” for custom events [duplicate]

    The following code is a simplified version of a module I am making where I want to implement custom “beforeopen” and “beforeclose” events. I want to be able to listen to these events, and cancel the open or close methods from continuing from inside the eventlistener function. For standard events, you can just do e.preventDefault() to cancel the default behavior assosiated with the event. This of course does not work for my custom event, but I want to know how I can make it work. Can I tell my event what the default action assosiated with the event is anyhow? Or are there other workarounds to make this work.

    const element = document.querySelector(".element");
    const openButton = document.querySelector(".openButton");
    
    function open() {
      element.dispatchEvent(new Event("beforeopen"));
      // if default is prevented, I want to stop the function from continuing!
      element.setAttribute("data-open", "");
    }
    
    element.addEventListener("beforeopen", (e) => {
      e.preventDefault();
    });
    
    openButton.addEventListener("click", () => {
      open();
    });
    .element {
      display: none;
    }
    .element[data-open] {
      display: block;
    }
    <div class="element">Element opened - Failed to prevent default</div>
    
    <button class="openButton">Open</button>

    Rokokbet Situs Toto Togel Online Resmi Dan Terpercaya di Indonesia 2024

    Selamat datang di website resmi Rokokbet, di sini kami akan memberikan sedikit penjelasan tentang Situs Toto 4D RokokBet Resmi Terpercaya. Yang sangat populer di kalangan Indonesia saat ini.RokokBet merupakan Platform penyedia permainan judi online yang menyediakan pelayanan 24 jam nonstop. Bukan itu saja, RokokBet juga memberikan hadiah kemenangan terbesar bagi para membernya.Hadiah yang bisa anda dapatkan sangat besar hanya dengan modal yang sangat terjangkau. Jadi untuk anda yang ingin bermain situs toto 4d kini sudah sangat mudah dan gampang.Anda hanya memerlukan sebuah smartphone dengan koneksi internet saja anda sudah bisa bermain situs toto online dengan sesuka hati anda. Namun, perlu anda ketahui di Indonesia sangat di larang keras tentang permainan judi online.

    Untuk taruhan nya juga sangat murah yang bisa anda lakukan, hanya dengan 100 perak saja anda bisa melakukan taruhan pada pasaran mana saja yang anda inginkan. Semakin banyak taruhan yang anda lakukan maka semakin besar juga kesempatan anda untuk mendapatkan hadiah terbesar nya.Nah berikut akan kami rangkum kan beberapa aplikasi e-wallet atau dompet digital di bawah ini:

    • Aplikasi DANA
    • Aplikasi OVO
    • Aplikasi LINKAJA
    • Aplikasi GOPAY
    • Aplikasi QRIS

    Tags:

    Rokokbet

    Rokokbet

    Rokokbet

    https://sayunieagtchurch.org/

    https://hanoufq8.com/-/rokokbet/

    https://yurylifshits.com/

    ROKOKBET > DAFTAR SITUS TOTO & TOGEL ONLINE RESMI TERPERCAYA

    Rokokbet Situs Toto Togel Online Resmi Dan Terpercaya di Indonesia 2024