how to a local server on hyer and node.js

I have been trying to open a by following an instructor online, but whenever she opens the localhost:3000 she gets an output.

But I am not getting anything it is showing, check your internet connection and even in Hyper it is giving some error when I try to type node server.js please help me.

enter image description here

I have tried changing the browser changing the code a few times but I was unable to figure out if it was a code problem or some linux error

State showing different values

I am receiving messages according to the statusuc state when state is active it should receive message or when it is inactive it should not update the array .

useEffect(() => {
console.log(statusc)
}, [statusc])
const handleJobReceived = (userdata) => {
console.log("The status of a person is " + statusc);

setJobData((prevState) => {
  if (statusc === "Active") {
    console.log("adding function run");
    return [...prevState, userdata];
  } else if (statusc === "Inactive") {
    return [...prevState];
  }
});
};


socket.on("job received", (userdata) => {
console.log("The status of a person is " + statusc);

handleJobReceived(userdata)
});

in this code i have also setup a useeffect which shows the value of statusc after changing in the same component i have assigned a button to log the value of statusc on clicking.

<button onClick={()=>{console.log(statusc)}}>Current statusc</button>

so the problem is that when statusc is changed and console in useffect shows active . and also on clicking button shows Active but console in socket shows inactive or simply the previous stage.

the console looks like
enter image description here

but where null is initial state of statusuc

How to convert Midi file variables to millisecond timestamps in javascript

I currently have a midi file parsed into a JSON object. Below is an image of the midi object in my browser console.

midi JSON object in browser console

My goal is to take this data (marked in red) and convert each item in the list to timestamps in milliseconds.

From my research, I know the meaning of the “deltaTime” property and I believe the “timeDivision” value of 192 (underlined in the image above) should be related to the tempo of the midi file.

However, because of my sparse knowledge of the maths behind midi file values, I don’t know how to convert all that information to milliseconds. I’m certain it must be a relatively simple math equation. But I’m really lost. I’m trying to build an object that should look like this and match the current millisecond time of the JSON object

image of expected end results

How do I convert the “timeDivision” value combined with the list of individual “deltaTime” values to milliseconds?

Even a basic answer would suffice. I just need to understand the math behind those values.
Thanks.

Why won’t v-for put out more profiles so I have an infinite scroll like effect?

Hi I have a firestore database where I am getting profiles from and then using v-for to show them all on a page but I want to put an infinite scroll in for better user experience.
This is my javascript composable code

import { projectFirestore } from "../Firebase/Config";
import { ref } from "vue"

const getPremium = () => {
    const Premium = ref([])
    const error = ref(null)

    
const load = async () => {
    try{
        const res = await projectFirestore.collection('Premium').limit(4).get()
        

        Premium.value = res.docs.map(doc => {
           console.log(doc.data())
           return {...doc.data(), id: doc.id}
        })
    }
    catch (err){
        error.value = err.message
        console.log(error.value)
    }
    const newPicturesCount = await load()
    if (newPicturesCount > 0) {
        return load() // More profiles to come
      }

      return console.log("done") // Done with the profiles
    }

    return { Premium, error, load }
}

export default getPremium

What I expected was that it would then v-for the rest of the results and make it so that the first profiles would load and then the next to make user experience better and with less load times but the profiles are being console logged as they load but they are not appearing in the v-for statement as I expected they would and it appears to get the same 4 profiles over and over which isn’t what I want heres the vue end for a full picture.

<div v-for =" Premiums in Premium" :key="Premiums.id" >
 <router-link :to="{ name: 'Samplepremium', params: { id: Premiums.id }}">
 <div class= "hover:scale-105 transition ease-in-out duration-300 bg-neutral-800 hover:bg-neutral-900 active:bg-neutral-900 text-neutral-400 font-bold rounded-xl">
  <br>
     <p class="text-xl">{{ Premiums.Name }}</p>
     <div class="relative">
     <img :src= "Premiums.Pic1"  class="object-contain px-1 inline-block w-96 h-44 md:w-60 md:h-80 lg:w-60 lg:h-80 xl:w-60 xl:h-80 2xl:w-60 2xl:h-80 transition ease-in-out duration-300">
     <p class="bg-red-700 text-slate-300 text-xl absolute top-0 w-full">{{ Premiums.detail1 }}</p>
     <p class="bg-red-700 text-slate-300 text-xl absolute bottom-0 w-full"> {{ Premiums.detail2 }} </p>
    </div>
     <div class="grid grid-cols-2 grid-rows-fit text-left ml-6">
     <p>Age:</p>
     <p>{{ Premiums.detail3 }}</p>
     <p>Location:</p>
     <p>{{ Premiums.detail4 }}</p>
     <p>Rates:</p>
     <p>{{ Premiums.detail5 }} /hr</p>
     <p>Phone:</p>
     <p>{{ Premiums.detail6 }}</p>
   
    </div><br>
  </div>
  </router-link>
  </div>
</template>

If anyone has any ideas on how to keep track of the document I’m up to and how to v-for profiles after the initial for I’d really appreciate it Thanks.

How can I effectively pass local user time to PHP from Javascript through a submitted form?

I’m building a tool that will be confusing to the user if it’s on server time due to timezones. I want to pass the local system time to PHP so DATETIME objects passed into the DB are based on their local time and date.

I found this: Convert JavaScript new Date() to php DateTime() which explains that I have to do weird stuff to the JS date function to make it compatible (using jquery to throw the time into the form just before submit):

$('input[name=now]').val('@' + Math.round(new Date().getTime()/1000));

On the PHP side, this is what I’m doing:

$local_time = (int)$_REQUEST['now'];
$today = new DateTime($local_time);

Simply, I’m trying to set the Datetime value to the passed JS value. I’ve been at this for an hour trying every page and guide I can find, but nothing is working. I keep getting various errors and, when it actually seemed to work, it was actually ignoring the $local_time value and just picked the server time instead.

With the code the way it is, I get the following error

Fatal error</b>:  Uncaught Exception: Failed to parse time string (0) at position 0 (0):
 Unexpected character in {pathtofile}.php:1394

NOTE: I have tried passing various JS formats (toGMTString, toISOString) and it either throws an error or ignores the value and uses server time instead.

React Parallel Api calling while Mapping Data

In the given code, there is a table with user items, and each item has a property called productHandle. By each productHandle i want to make api request which will gimme a productTitle and productImage I need to display this information in a new column in the table. How can I do this efficiently without causing long load times? Should I use new Promise() or the promise.all method? any example?

Here each user have a productHandle. I wanna make API request for each item with that productHandle which will return productTitle and an image and i will display it on table new column.

<table className="table table-striped table-bordered table-hover">
      <thead>
        <tr>
          <th>User Id</th>
          <th>Firstname</th>
          <th>Lastname</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Fax</th>
          <th>Address</th>
        </tr>
      </thead>
      <tbody>
        {users.map((user: any, index: number) => (
          <tr key={index}>
            <td>{user.userId}</td>
            <td>{user.firstname}</td>
            <td>{user.lastname}</td>
            <td>{user.email}</td>
            <td>{user.phone}</td>
            <td>{user.fax}</td>
            <td>{user.address}</td>
          </tr>
        ))}
      </tbody>
    </table>

console.log does not work in frontend JavaScript file

I’m using vscode and have node.js installed. When using console.log statements in the index.js file (backend), the output shows up in the debug console. However, when using a console.log statement in the script.js file the output doesn’t show up.

The output doesn’t appear in problems, output or terminal either

This is probably a really easy fix but does anyone know how to fix this?

ERROR Error: Canvas is already in use. Chart with ID ‘0’ must be destroyed before the canvas with ID ‘prueba’ can be reused

Hola a todos tengo el siguiente mensaje de error al momento de poner dos graficas en un componente de angular el primer problema es que me duplicaba la etiqueta canvas, lo segundo es que solo me mostraba solo una grafica y no la otra, sino que solo una de las dos me mostraba estoy trabajando con angular, y con las bibliotecas de chart.js, tengo dos typescript es uno para cada grafica y el template que toman los dos es uno solo, ademas de que lo que hice fue primero fue tratar de cambiar la variable que guarda la instancia de las clases llamada chart pero al parecer tampoco puedo ya que si trato de nombrar una nueva variable en un typescript de las graficas tambien me pide la variable en el otro typescript, por lo cual encontre otro archivo que al parecer manipula estos dos archivos de las graficas y por eso no me deja crear nuevas variables dentro de los typescript sin que esten en los dos archivos

El primer typescript es este que realiza una grafica de barra

import { Component } from '@angular/core';
import { ReCaptchaV3Service } from 'ng-recaptcha';
import { ProgramasSocialesService } from '../../../services/programas-sociales.service';
import { AlertasService } from 'src/app/services/alertas.service';
import {Chart as ChartJS} from 'chart.js/auto';

@Component({
  selector: 'stacked-column100-chart-indexlabel',
  templateUrl: 'chart.component.html',
})
export class StackedColumn100ChartIndexlabelComponent {

  dataPoints: any = [];
  chartOptions = {};
  chart = {}; //----------------------
  title:any = '';
  constructor(
    private recaptchaV3Service: ReCaptchaV3Service,
    private service: ProgramasSocialesService,
    private alertasService: AlertasService
  ){
    this.recaptchaV3Service.execute('graficaBarrasProgramasSociales').subscribe({
      next: (token) => {
        this.service.getDataProgramasSocialesBarras(token).subscribe({
          next: (response) => {
            console.log('data grafica', response);
            if (response.length <= 0) {
              this.alertasService.alertaErrorInfo();
            } else {
              this.title = "Población beneficiada";
              this.dataPoints.dataPointsHombres = response['dataPointsHombres'];
              this.dataPoints.dataPointsMujeres = response['dataPointsMujeres'];
              this.dataPoints.dataPointsNoEspecificado = response['dataPointsNoEspecificado'];
              this.chart  = new ChartJS('prueba', {
                type: 'bar',
                data: {
                  labels: this.dataPoints.dataPointsHombres.map(data => data.label),
                  datasets: [{
                    label: 'Hombres',
                    data: this.dataPoints.dataPointsHombres.map(data => data.y),
                    borderWidth: 1
                  }, {
                    label: 'Mujeres',
                    data: this.dataPoints.dataPointsMujeres.map(data => data.y),
                    borderWidth: 1
                  }, {
                    label: 'No Especificado',
                    data: this.dataPoints.dataPointsNoEspecificado.map(data => data.y),
                    borderWidth: 1
                  }]
                },
                options: {
                  scales: {
                    y: {
                      beginAtZero: true,
                    },
                  },
                },
              });
            }
          },
          error: (error: Error) => {
            this.alertasService.alertaErrorInfo();
            console.error(error);
          },
        });
      },
      error: (error: Error) => {
        this.alertasService.alertaErrorTokenCaptcha();
        console.error(error);
      },
    });
  }
}

El segundo es este que realiza una barra de pastel

import { Component } from '@angular/core';
import { ReCaptchaV3Service } from 'ng-recaptcha';
import { ProgramasSocialesService } from '../../../services/programas-sociales.service';
import { AlertasService } from 'src/app/services/alertas.service';
import {Chart} from 'chart.js/auto';

@Component({
  selector: 'multiple-axis',
  templateUrl: 'chart.component.html',
})
export class MultiplsAxisChartComponent {

  total: number;
  dataPoints: any[];
  chartOptions = {};
  chart: any = [];
  title: any = '';
  constructor(
    private recaptchaV3Service: ReCaptchaV3Service,
    private service: ProgramasSocialesService,
    private alertasService: AlertasService
  ){

  }

  ngOnInit(){
    this.getDataProgramasSocialesPastel();
  }

  private getDataProgramasSocialesPastel(){
    this.recaptchaV3Service.execute('graficaPastelProgramasSociales').subscribe({
      next: (token) => {
        this.service.getDataProgramasSocialesPastel(token).subscribe({
          next: (response) => {
            console.log('data grafica pastel', response);
            if (response.length <= 0) {
              this.alertasService.alertaErrorInfo();
            } else {
              this.handleDataProgramasSocialesPastel(response);
            }
          },
          error: (error: Error) => {
            this.handleDataProgramasSocialesPastelError(error);
          },
        });
      },
      error: (error: Error) => {
        this.handleDataProgramasSocialesPastelError(error);
      },
    });
  }

  private handleDataProgramasSocialesPastel(response){
    this.total = response['total'];
    this.dataPoints = response['dataPoints'];
    this.initializeChartOptions();
  }

  private handleDataProgramasSocialesPastelError(error){
    this.alertasService.alertaErrorInfo();
    console.error(error);
  }

  private initializeChartOptions() {
    this.title =  "Número total de beneficiadas(os): " + this.total;
    this.chart = new Chart('prueba', {
      type: 'pie',
      data: {
        labels: this.dataPoints.map(data => data.name + ": " + data.y),
        datasets: [{
          label: ' Número de beneficiad@s',
          data: this.dataPoints.map(data => data.y),
          backgroundColor: this.dataPoints.map(data => data.color),
          borderWidth: 1
        }]
      },
    });
  }
}

El template que los dos estan usando tiene lo siguiente

<canvas id="prueba2" style="width: 100%; margin: 0 auto;">{{chart}}</canvas> -->
<div class="container">
  <h3><strong>{{title}}</strong></h3>
  <canvas id="prueba" style="width: 100%; margin: 0 auto;">{{chart}}</canvas>
</div>

El archivo que al parecer manipula los typescript de las graficas tiene lo siguiente

/*
CanvasJS Angular Charts - https://canvasjs.com/
Copyright 2023 fenopix

--------------------- License Information --------------------
CanvasJS is a commercial product which requires purchase of license. Without a commercial license you can use it for evaluation purposes for upto 30 days. Please refer to the following link for further details.
https://canvasjs.com/license/

*/
/tslint:disable/
/eslint-disable/
/jshint ignore:start/
import { Component, AfterViewInit, OnChanges, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
declare var require: any;
var CanvasJS = require('./canvasjs.min');

@Component({
  selector: 'canvas',
  template: '<div id="{{chartContainerId}}" [ngStyle]="styles"></div>'
})

class CanvasJSChart implements AfterViewInit, OnChanges, OnDestroy {
    static _cjsChartContainerId = 0;
    chart: any;
    chartContainerId: any;
    prevChartOptions: any;
    shouldUpdateChart = false;

    @Input()
        options: any;
    @Input()
        styles: any;

    @Output()
        chartInstance = new EventEmitter<object>();

    constructor() {
        this.options = this.options ? this.options : {};
        this.styles = this.styles ? this.styles : { width: "100%", position: "relative" };
        this.styles.height = this.options.height ? this.options.height + "px" : "400px";

        this.chartContainerId = 'canvasjs-angular-chart-container-' + CanvasJSChart._cjsChartContainerId++;
    }

    ngDoCheck() {
        if(this.prevChartOptions != this.options) {
            this.shouldUpdateChart = true;
        }
    }

    ngOnChanges() {
        //Update Chart Options & Render
        if(this.shouldUpdateChart && this.chart) {
            this.chart.options = this.options;
            this.chart.render();
            this.shouldUpdateChart = false;
            this.prevChartOptions = this.options;
        }
    }

    ngAfterViewInit() {
      this.chart = new CanvasJS.Chart(this.chartContainerId, this.options);
      this.chart.render();
      this.prevChartOptions = this.options;
      this.chartInstance.emit(this.chart);
    }

    ngOnDestroy() {
        if(this.chart)
            this.chart.destroy();
    }
}

export {
    CanvasJSChart,
    CanvasJS
};
/tslint:enable/
/eslint-enable/
/jshint ignore:end/

Y el html donde los componentes de las graficas donde los mando llamar esta de la siguiente manera:

<app-loading *ngIf="loading"></app-loading>
<div class="container mt-4 mb-5">

  <section class="text-center animate_animated animate_fadeInDown">
    <h3 class="fw-bold">Programas Sociales</h3>
    <mat-divider></mat-divider>
  </section>

  <section class="mt-3 animate_animated animate_fadeIn">
    <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel" data-bs-touch="true">
      <div class="carousel-inner">
        <div *ngFor="let img of imagenes; let i = index" [ngClass]="{'active': i == 0 }" class="carousel-item">
          <img [src]="img.url" class="d-block w-100 imgs-carousel" alt="...">
        </div>
      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators"
        data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Siguiente</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators"
        data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Anterior</span>
      </button>
    </div>
  </section>
  <br><br><br>

  <section class="rounded animate_animated animate_fadeInUp">
    <div class="text-center mb-3">
      <button (click)="displayFilters()" mat-raised-button color="primary">
        <i [ngClass]="!isShowFilters ? 'fa-chevron-down' : 'fa-chevron-up'" class="fa-solid ">
        </i> Filtros avanzados
      </button>
    </div>
    <div class="row" *ngIf="isShowFilters">

      <app-buscador></app-buscador>
    </div>
  </section>

  <section class="mt-4 animate_animated animate_fadeInUp">
    <h3 class="fw-bold text-center">Estadísticas Generales</h3>
    <mat-divider class="mt-2 mb-2"></mat-divider>
  </section>

  <section class="mt-5">
     <multiple-axis></multiple-axis>
  </section>

  <section class="mt-5">
      <stacked-column100-chart-indexlabel></stacked-column100-chart-indexlabel>
  </section>

</div>

Llevo dias buscando informacion pero no encuentro nada lo unico que creo que sea posible es que debo de cambiar el nombre de la variable que instancia a la clase ademas, o la otra es rehacer los componentes para evitar el archivo que parece manipular los typescript de las graficas y/o ademas que cada typescript tenga su propio archivo html para evitar conflictos

ReactJS – Custom hook return function doesn’t store actual data from internal state

I have a custom hook useNotifications for Notification widget. This hook returns an array with the next elements (it’s similar to ant.design message api):

  • add: function to add a new notification
  • remove: function which gets a notification id and removes the notification
  • contextHandler: JSX which is passed into component’s render

When user calls add they get an id which can be used to remove the notification

The problem is dedicated to remove function particularly. Since I call this function right after I add new notification, the function receives a copy of old list so there’s no new element and it throws an error. How can I fix it so there’s same API for the Component uses that?

useNotification hook
How I use it

Codesandbox (for test I did setTimeout which calls remove() in 3 seconds): https://codesandbox.io/s/goofy-smoke-5q7dw3?file=/src/App.js:405-440

Modifying simple javascript

I have a js based color-picking program that I’ve modified from one I found online. It involves a color picker for one CSS overlay. I’ve been trying to change it so that I have a second color picker for a second CSS overlay AND so that the color picker is a set of limited pre-defined color options.

I will be grateful for any assistance!

Here’s my code:

HTML:

<div class="couch">

    <svg id="js-one" class="couch__overlay" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="none" width="800" height="800">
    <defs>
    <path class="cls-1" d="m667.5,422.3c40.31,2.4-289.87,36.46-291,73-1.36,44.18-62.33,83.81-109,65-37.44-15.09-60.51-65.7-42-102,14.06-27.58,417.33-37.47,442-36Z" id="a"/>
    </defs>
    <use xlink:href="#a"/>
    </svg>

    <img class="couch__img" src="test.png" alt="">
    </div>

    <div class="colours">
    <div class="colours__labels">
    <span>Choice 1</span>

    </div>

    <div class="colours__inputs">
    <input id="js-color-1" class="jscolor {onFineChange:'updateCouch(this)'}" value="FCFF4D">

    </div>
    </div>
    <!-- partial -->
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.js'></script><script  src="./script.js"></script>

CSS:

body,
html {
  height: 100%;
  display: flex;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  justify-content: center;
  align-items: center;
  font-family: arial;
  font-size: 12px;
}
.colours {
  position: absolute;
  bottom: 1em;
  display: flex;
  flex-direction: column;
}
.colours__labels {
  display: flex;
  margin-bottom: 0.5em;
}
.colours__labels span {
  display: block;
  flex: 2;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 0.9em;
  color: white;
  text-shadow: 0px 0px 4px black;
}
.colours__labels span:first-child {
  flex: 1;
}
.colours__inputs {
  display: flex;
}
.colours .jscolor {
  display: block;
  border: 0;
  height: 40px;
  width: 60px;
  margin: 0;
  text-align: center;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
  cursor: pointer;
}
.colours .jscolor:first-child {
  border-radius: 6px 0 0 6px;
}
.couch {
  width: 800px;
  height: 800px;
  transform: scale(0.66);
  position: relative;
  transition: 0.25s ease-in-out;
}

.couch__overlay, .couch__img {
  position: absolute;
  top: 0;
  left: 0;
}
.couch__overlay {
  z-index: 2;
  fill: #fcff4d;
  mix-blend-mode: multiply;
}
.couch__overlay.fade {
  transition: 0.6s ease-in-out;
}


@media (max-width: 800px) {
  .couch {
    transform: scale(0.5);
  }
}
@media (max-width: 800px) {
  .couch {
    transform: scale(0.38);
  }
}
@media (max-width: 800px) {
  .couch {
    transform: scale(0.4);
  }
}

}

JS:


function updateCouch(picker, string) {
  couch.style.fill = picker.toHEXString();

}

function updateBackgroundL(picker, randArray) {
 if (!randArray) {
  background[1] = picker.toHEXString();
  } else {
    background[1] = randArray[1];
  }
}

I’ve tried tweaking the existing code, but it’s not working (my js knowledge is very minimal)

vite-plugin-pwa use custom fetch interceptor for ‘/api’ routes

I would like to develop a Vue Progressive Web App which uses the stock standard features of vite-PWA-plugin for all requests sent to any path other than those beginning with ‘/api/’. However for requests going to a path starting with ‘/api’, I would like to handle it with code which uses the IndexedDB api. I would also like to hook into the install event of the serviceworker. If I were to be writing my own service worker, I would use something like:

let db:Dexie | null  = null;

self.addEventListener('install', (event) => {
  try {
    db = new Dexie("FrenemyDatabase");
    db.version(1).stores({
      friends: `id,name,age`,
      enemies: `id,name,age`
    });
    event.waitUntil(db.open())
  } catch(e) {
    event.waitUntil(Promise.reject(e))
  }
});

Is there a way to keep all the functionality of vite-PWA-plugin for all non /api paths, but provide my an additional function to the service worker ‘install’ event and a replacement function for fetch requests to ‘/api’ paths?

Continuous Carousel using React and styled-components

I’m trying to recreate a carousel that is continuous using react and styled-components without any dependencies. The continuous carousel should work by appending the first element to the last once it reaches the last element . I’m new to react and styled-components.

example : Continuous Carousel

<p><code>wrapAround: true</code></p>

<!-- Flickity HTML init -->
<div class="gallery js-flickity"
  data-flickity-options='{ "wrapAround": true }'>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
  <div class="gallery-cell"></div>
</div>```

this done by Flickity. I'm trying to recreate the functionality using react and styled-components only 

Dynamically load audio

I’m trying to implement TTS from Elevenlabs for a chatbot. I’m using React and Express to handle the request. I receive the request and write it to an audio file named audio.mp3. I then send the file name as the response and then save that file name in a use state variable. For every request, I modify the current audio.mp3 file with the new audio.

app.post("/labs", async (req, res) => {
  try {
    const message = req.body.message;
    const voice = req.body.voice;
    const response = await axios.post(
      `https://api.elevenlabs.io/v1/text-to-speech/${voice}`,
      { text: message },
      {
        headers: {
          accept: "audio/mpeg",
          "Content-Type": "application/json",
          "xi-api-key": config.ELVN_API_KEY,
        },
        responseType: "stream",
      }
    );
    if (response.status !== 200)
      throw new Error("Oops, something unexpected happened.");

    response.data.pipe(fs.createWriteStream("../client/public/audio.mp3"));
    res.send(JSON.stringify({ file: "audio.mp3" }));
  } catch (error) {
    res.send(error);
    console.log(error);
  }
});

I then use the variable if it’s not null.

{audio && <audio key={cacheBuster} autoPlay controls src={audio} />}

The first time I get back a response the audio works. However, any subsequent requests don’t work and use the first version of the file. I’ve attempted to implement a cachebuster because I recognize that the browser is using the cached version of the file but it’s not working for me and I’ve also tried .load but I’m using Typescript and I got not a function error. I don’t want to create new files for every request because I want to deploy the site and I’m not sure how that would affect it performance-wise. I’m also not sure if those files are only stored for the session. If anyone has any information about that or any suggestions on how to accomplish this problem better I would greatly appreciate it.

Firebase can’t make call to cloud function because of cross origin policy

As the title suggests, I have a web app that calls a Firebase cloud function, but it doesn’t work because of a cross-origin policy. I’ve seen many solutions on this site, but none work. I tried an answer from another StackOverflow question but nothing worked at all.

code in index.html:

            firebase
            .functions()
            .httpsCallable("addMessage")()
            .then((res) => {
                console.log(res);
            });

code in index.js (the cloud function):

exports.addMessage = onRequest(async (req, res) => {
    // Grab the text parameter.
    const original = req.query.text;
    // Push the new message into Firestore using the Firebase Admin SDK.
    const writeResult = await getFirestore().collection("messages").add({ original: original });
    // Send back a message that we've successfully written the message
    res.set("Access-Control-Allow-Origin", "*");
    res.json({ result: `Message with ID: ${JSON.stringify(original)} added.` });
});

the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-mysecretsite.cloudfunctions.net/addMessage. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 403.

I’m very confused on how these solutions even worked for other people as this seems to be a client-side problem and nothing added to the cloud function should fix it. please help!