Why Am I Receiving a 404 Error When Making a POST Request with Axios in a React Vite App?

I’m developing a React application with Vite and implementing user registration functionality.The goal is to send a POST request using Axios to an Express server running on localhost:8800.

However I encounter a 404 Not Found error when making the POST request for user registration.
The error occurs even though the server is running and the endpoint seems correctly defined.

import axios from "axios"

const Register = () => {
  const [inputs, setInputs] = useState({
    username:"",
    email:"",
    password:"",
  })

  const handleChange = e => {
    setInputs(prev=>({...prev, [e.target.name]: e.target.value}))

  }
  const handleSubmit = async e =>{
    e.preventDefault()
    try{
      const res = await axios.post("http:localhost:8800/auth/register", inputs)
      console.log(res)
    }catch(err){
      console.log(err)
    }
  }
///
}

export default Register;

I’ve checked the server URL and confirmed that the Express server is running on the specified port.

I’ve also verified that the /register route is correctly set up in my Express app.
app.use("/server/auth", authRoutes)

I tried adding the proxy vite.config.js file but still no luck

What could be the reason for receiving a 404 error on a POST request to localhost:8800 for user registration, and how can I resolve it?
Are there specific configurations in Vite or Express that I might be missing for handling such requests?

here is my full error message
//
localhost:8800/server/auth/register:1
Failed to load resource: the server responded with a status of 404 (Not Found)
Register.jsx:22
AxiosError
code
:
“ERR_BAD_REQUEST”
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
“Request failed with status code 404”
name
:
“AxiosError”
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: ”, status: 404, statusText: ‘Not Found’, headers: AxiosHeaders, config: {…}, …}
stack
:
“AxiosError: Request failed with status code 404n at settle (http://localhost:5173/node_modules/.vite/deps/axios.js?v=afb224e6:1204:12)n at XMLHttpRequest.onloadend (http://localhost:5173/node_modules/.vite/deps/axios.js?v=afb224e6:1421:7)”
[[Prototype]]
:
Error

Next.js: `onSubmit` not executing callback function

In my Next.js module, I have a form declared as follows:

<form onSubmit = {() => {
async() => await getCertificate(id)
.then(async resp => await resp.json())
.then(data => console.log(data))
.catch(err => console.error(err))
console.log("getCertificate completed")
}}>

Function getCertificate() is defined in the same .tsx file as:

async function getCertificate(id: string) : Promise<Response> {
  console.log("in getCertificate")
  const resp = await fetch(`${serverUri}/certs/${id}`)
  console.log(`Response data: ${await resp.json()}`)
  return resp
}

It appears that getCertificate() is not getting called at all. While the final console.log("getCertificate completed") inside my onSubmit handler is executing correctly, none of the console.log() statements insisde getCertificate() are being executed.

No errors are being thrown or logged to the console. The only thing appearing in the console (in addition to getCertificate completed), is Navigated to http://localhost:3000/?certId=my_cert_id.

Any idea why it is behaving like this?

(The only other things to note are that my .tsx file is decorated with 'use client' since I am utilizing a client library for certain other functionalities, and that my form definition is inside the return statement of an export default function. Everything else works as expected except for getCertificates() not being hit).

Correct method to import front-end JS npm modules when using TypeScript

I have a .NET Core ASP site. My aim is to use Razor for the pages, and TypeScript for the front-end, with proper use of JS modules.

My challenge is using npm packages, e.g. socket-io (client), for various client side bits.

I npm install the package, and then in my TypeScript:

import { io, Socket } from "socket.io-client";

compiles just fine, and the IDE is happy, as it can resolve the module (in node_modules).

But at runtime, the browser cannot, and it all fails.

I’m assuming that I need to use something like Webpack to follow the dependencies in all the TypeScript-generated JS, notice that it imports npm modules, and generate a single JS file with all those dependencies. Then include that file as a <script type="module" /> import on all my pages.

  1. Most importantly, is this indeed the correct approach?

  2. I’ve attempted this with tsc-bundle, Vite, and Webpack, and cannot coerce the output file to be (what appears to me) to be an ESM. Instead it’s an IIFE, and so the import ... line in the TS (and generated JS) will surely not work. Is my thinking correct on this?

Getting the error: “Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’) at xhttp.onreadystatechange” after getting output once

I am fetching data (temperature, humidity and gas) from sensor (DHT11 and MQ4) using ESP8266 (NodeMCU) and show them in the website, everything works fine in the view but when I go to console I see this error:

"(index):18 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
    at xhttp.onreadystatechange ((index):18:56)
xhttp.onreadystatechange @ (index):18
XMLHttpRequest.send (async)
updateData @ (index):24
setInterval (async)
(anonymous) @ (index):26 "

Here is the Arduino IDE code that I am using:

include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "DHTesp.h"

#define DHTpin 14    //D5 of NodeMCU is GPIO14
DHTesp dht;



const char* ssid = "Tasnim";       // Enter SSID here
const char* password = "peara2304";  // Enter Password here

ESP8266WebServer server(80);




// MQ-4 Gas Sensor
uint8_t MQ4Pin = A0;

float Temperature = dht.getTemperature();  
 float Humidity = dht.getHumidity();        
 float  GasValue = analogRead(MQ4Pin);       

void setup() {
  Serial.begin(115200);
  delay(10);

  dht.setup(DHTpin, DHTesp::DHT11);
  pinMode(MQ4Pin, INPUT);



  Serial.println("Connecting to ");
  Serial.println(ssid);

  // Connect to your local Wi-Fi network
  WiFi.begin(ssid, password);

  // Check Wi-Fi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected..!");
  Serial.print("Got IP: ");
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, handle_OnConnect);
  server.on("/data", HTTP_GET, handle_Data);
  server.onNotFound(handle_NotFound);

  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

void handle_OnConnect() {
 float Temperature = dht.getTemperature();  
 float Humidity = dht.getHumidity();        
 float  GasValue = analogRead(MQ4Pin);       

  server.send(200, "text/html", SendHTML(Temperature, Humidity, GasValue));
}

void handle_Data() {
  String data = "{"temperature":" + String(Temperature) +
                ","humidity":" + String(Humidity) +
                ","gasValue":" + String(GasValue) + "}";
  server.send(200, "application/json", data);
}

void handle_NotFound() {
  server.send(404, "text/plain", "Not found");
}

String SendHTML(float Temperaturestat, float Humiditystat, float GasValueStat) {
  String ptr = "<!DOCTYPE html> <html>n";
  ptr += "<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">n";
  ptr += "<title>ESP8266 Weather and Gas Report</title>n";
  ptr += "</head>n";
  ptr += "<body>n";
  ptr += "<div id="webpage">n";
  ptr += "<h1>ESP8266 NodeMCU Weather and Gas Report</h1>n";
  ptr += "<p>Temperature: " + String(Temperaturestat) + "°C</p>n";
  ptr += "<p>Humidity: " + String(Humiditystat) + "%</p>n";
  ptr += "<p>Gas Value: " + String(GasValueStat) + "</p>n";
  ptr += "</div>n";
  ptr += "<script>n";
  ptr += "function updateData() {n";
  ptr += "  var xhttp = new XMLHttpRequest();n";
  ptr += "  xhttp.onreadystatechange = function() {n";
  ptr += "    if (this.readyState == 4 && this.status == 200) {n";
  ptr += "      var data = JSON.parse(this.responseText);n";
  ptr += "      document.getElementById('temperature').innerHTML = 'Temperature: ' + data.temperature + '°C';n";
  ptr += "      document.getElementById('humidity').innerHTML = 'Humidity: ' + data.humidity + '%';n";
  ptr += "      document.getElementById('gasValue').innerHTML = 'Gas Value: ' + data.gasValue;n";
  ptr += "    }n";
  ptr += "  };n";
  ptr += "  xhttp.open('GET', '/data', true);n";
  ptr += "  xhttp.send();n";
  ptr += "}n";
  ptr += "setInterval(updateData, 1000);n";
  ptr += "function autoRefresh(){";
  ptr += "window.location = window.location.href;";
  ptr += "}n";
  ptr += "setInterval('autoRefresh()',100000)";
  ptr += "</script>n";
  ptr += "</body>n";
  ptr += "</html>n";
  return ptr;
}

enter image description here

I am trying to fetch data as API to be called using another server, so the data on the console is needed for me.
Please do help me out, I am a beginner in this works.

How to send the user programmatically to another route?

Given is a VueJS 3 application, based on Quasar and I am struggling to use the Router programmatically.

The issue is described best like this:

1. The Problem

When I push the User to another route, only the URL in the browser will be updated, but the corresponding Component will not get rendered.
I have to manually refresh the web page in the Webbrowser in order to get the corresponding component rendered properly.

2. Code

I have published a full working example on GitHub: https://github.com/itinance/quasar-
router-bug

The router is configured in history-mode, but this doesn’t matter as the issue appears also in the hash-mode.

Here are my routes:

import { RouteRecordRaw } from 'vue-router';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('layouts/MainLayout.vue'),
    children: [{ path: '', component: () => import('pages/IndexPage.vue') }],
  },

  {
    path: '/test',
    name: 'test',
    component: () => import('layouts/MainLayout.vue'),
    children: [{ path: '', component: () => import('pages/TestPage.vue') }],
  },

  // Always leave this as last one,
  // but you can also remove it
  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];

export default routes;

Here is my Index-Component, that contains a button where I want to send the user programmatically to another page:

<template>
  <q-page class="row items-center justify-evenly">

    <div class="q-pa-md example-row-equal-width">
      <div class="row">
        <div>INDEX PAGE</div>
      </div>


      <div class="row">
        <div>
          In order to navigate to the test page, you need to manually reload the page after clicking the button.
          Otherwise, only a white page will be rendered.

          <q-btn align="left" class="btn-fixed-width" color="primary" label="Go to test page" @click="doRedirect"/>
        </div>
      </div>


    </div>
  </q-page>
</template>

<script lang="ts">
import {Todo, Meta} from 'components/models';
import ExampleComponent from 'components/ExampleComponent.vue';
import {defineComponent, ref} from 'vue';
import {dom} from 'quasar';
import {useRouter} from 'vue-router';

export default defineComponent({
  name: 'IndexPage',
  computed: {
    dom() {
      return dom
    }
  },
  components: {},
  setup() {

    const router = useRouter();

    const doRedirect = () => {
      console.log('doRedirect');
      router.push({name: 'test'});
    }
    return {doRedirect};
  }
});
</script>

And this is the test-component, which is the target component where I want to use send:

<template>
  <q-page class="row items-center justify-evenly">

    <div class="q-pa-md example-row-equal-width">
      <div>
        TEST PAGE

        this will only be rendered after manual page-reload

      </div>
    </div>
  </q-page>
</template>

<script lang="ts">
import { Todo, Meta } from 'components/models';
import ExampleComponent from 'components/ExampleComponent.vue';
import { defineComponent, ref } from 'vue';

export default defineComponent({
  name: 'TestPage',
  setup () {
    return { };
  }
});
</script>
  1. What happens instead?

3.1 This is the index page, containing the button that shall send the user to another page:

enter image description here

3.2. When I click on the Button, the URL will be updated correctly but the test-component won’t get rendered at all:

enter image description here

3.3. But when I refresh the web browser now manually (or navigate to that particular URL), it will render the test component:

enter image description here

#4. Question

What am I doing wrong? How can I programmatically send the user to the test-page so that not only will the URL be updated but also the component will get rendered automatically, once the URL has changed?

As already mentioned, I also published a small test project that makes the described issue reproducible: https://github.com/itinance/quasar-router-bug

Chrome seekbar issue when recording a video and playing it via RecordRTC

I am using RecordRTC to record and play the video in my webpage however after recording the video and trying to play it back on Chrome or Edge, the seekbar is at the end and eventually after sometime it goes back to the time it is playing at.

      async startRecording() {
    try {
      this.recordRTC = RecordRTC(this.mediaStream, {type: 'video'});
      this.recordRTC.startRecording();
    } catch (error) {
      alert('Access for microphone and webcam not granted');
    }
  }

 stopRecording() {
    this.recordRTC.stopRecording(() => {
      this.stopStream();
      const blob = this.recordRTC.getBlob();
      this.videoURL = URL.createObjectURL(blob);
      this.recordedVideoElement.nativeElement.src = this.videoURL;
    });
  }

         <video #recordedVideo>
            <source [src]="this.videoURL">
          </video>      async startRecording() {
    try {
      this.recordRTC = RecordRTC(this.mediaStream, {type: 'video'});
      this.recordRTC.startRecording();
    } catch (error) {
      alert('Access for microphone and webcam not granted');
    }
  }

<video #recordedVideo>
            <source [src]="this.videoURL">
          </video>

However on Firefox there is no such issue, am I doing something wrong or do I need to process the video in some form? Any help is appreciated.

Fetch API Url with Arguments [duplicate]

I have this [working] HTML/Javascript code to fetch data from a json API.

function getElement(id) {
  return document.getElementById(id);
}

fetch('https://api-url.tld')
.then(res => res.json()
.then(json => {
  getElement('total_clicks').innerText = json["stats"]["total_clicks"];
}));

But now I want to use a different API, with different requirements. I can retrieve the json output with the following curl command:

curl -X 'GET' 
  'https://api-url.tld' 
  -H 'accept: application/json' 
  -H 'X-Api-Key: APIKEY'

This is an example output of it:

{
  "visits": {
    "nonOrphanVisits": {
      "total": 0,
      "nonBots": 0,
      "bots": 0
    },
    "data": 0,
  }
}

What should the first code look like so that I get the same result? At the end of "nonOrphanVisits" -> "total": 0 should be inserted here in getElement('total_clicks').innerText.

Thank you for Answers!

NextAuth register redirects to /api/auth/error

I’ve been following one guide from YT about using Next.js 13 to build E-Shop, and made it to routes. 10 minutes in and I’m stuck. So I dont know. I’m new to this, could someone please hep me

Here’s what I have:

pagesapiauth[…nextauth].ts

import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import CredentialsProvider from "next-auth/providers/credentials"
import { PrismaAdapter } from "@next-auth/prisma-adapter"
import prisma from "@/libs/prismadb"
import bcrypt from "bcrypt"

export default NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
    }),
    CredentialsProvider({
        name: 'credentials',
        credentials:{
            email:{
                label: 'email',
                type: 'text'
            },
            password: {
                label: 'password',
                type: 'password'
            },
        },
        async authorize(credentials){
            if(!credentials?.email || !credentials?.password){
                throw new Error('Invalid email or password')
            }

            const user = await prisma.user.findUnique({
                where: {email: credentials.email},
            })

            if(!user || !user?.hashedPassword){
                throw new Error('Invalid email or password')
            }

            const isCorrectPassworg = await bcrypt.compare(
                credentials.password,
                user.hashedPassword
            )

            if(!isCorrectPassworg){
                throw new Error('Invalid email or password') 
            }

            return user
        }
    })
  ],

  pages:{
    signIn: "/login",
  },
  debug: process.env.NODE_ENV === 'development',
  session: {
    strategy:'jwt',
  },
  secret: process.env.NEXTAUTH_SECRET
})

appregisterRegisterForm.tsx

"use client";

import { useState } from "react";
import Input from "../components/inputs/input";
import { FieldValues, SubmitHandler, useForm } from "react-hook-form";
import Button from "../components/Button";
import Link from "next/link";
import { AiOutlineGoogle } from "react-icons/ai";
import axios from "axios";
import { signIn } from "next-auth/react";
import { toast } from "react-hot-toast";
import { useRouter } from "next/navigation";

const RegisterForm = () => {
  const [isLoading, setIsLoading] = useState(false);
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FieldValues>({
    defaultValues: {
      name: "",
      email: "",
      password: "",
    },
  });

  const router = useRouter();

  const onSubmit: SubmitHandler<FieldValues> = (data) => {
    setIsLoading(true);

    axios
      .post("/api/register", data)
      .then(() => {
        toast.success("Account created");

        signIn("credentials", {
          email: data.email,
          password: data.password,
          redirect: false,
        }).then((callback) => {
          if (callback?.ok) {
            router.push("/my-characters");
            router.refresh();
            toast.success("Logged In");
          }

          if (callback?.error) {
            toast.error(callback.error);
          }
        });
      })
      .catch(() => {
        toast.error("Something went wrong");
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return (
    <>
      <h1 className="flex flex-col items-center text-3xl font-bold text-slate-700">
        Sign Up
      </h1>
      <Button
        outline
        label="Sign up with Google"
        icon={AiOutlineGoogle}
        onClick={() => {}}
      />
      <hr className="bg-slate-300 w-full h-px" />
      <Input
        id="name"
        label="Name"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
      />
      <Input
        id="email"
        label="Email"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
      />
      <Input
        id="Password"
        label="Password"
        disabled={isLoading}
        register={register}
        errors={errors}
        required
        type="password"
      />
      <Button
        label={isLoading ? "Loading" : "Sign Up"}
        onClick={handleSubmit(onSubmit)}
      />
      <p className="text-sm">
        Already have an account?{" "}
        <Link className="underline" href="/login">
          Log In
        </Link>
      </p>
    </>
  );
};

export default RegisterForm;

appapiregisterroute.ts

import bcrypt from "bcrypt"
import prisma from "@/libs/prismadb"
import { NextResponse } from "next/server"

export async function POST(request: Request){
    const body = await request.json()
    const {name, email, password} = body

    const hashedPassword = await bcrypt.hash(password, 10)

    const user = await prisma.user.create({
        data:{
        name, 
        email, 
        hashedPassword
        },
    })

    return NextResponse.json(user)
}

libsprismadb.ts

import { PrismaClient } from '@prisma/client'

declare global{
    var prisma: PrismaClient | undefined
}

const client = globalThis.prisma || new PrismaClient()

if(process.env.NODE_ENV !== "production") globalThis.prisma = client;

export default client;

Guy from video tries registration and it automatically redirects him to the page he specified but when I try, I get an error. So after seing this problem I tried to open link in Incognito Mode(did nothing). Path to […nextauth].ts is correct(checked 5 times). I’ve also checked my DB and everything got there correctly. In Chrome console I have this error GET http://localhost:3000/api/auth/error 404 (Not Found)

Clipboard API and HTML for email signature generator

I’m building a simple email signature generator and I’ve run into the deprecated document.execCommand('copy') method.

I’ve got a div that holds the styled table for the footer, but when I run my try block and paste it into Outlook, the output is not what I expect.

const contentToCopy = document.getElementById(contentElId);
const range = new Range();
range.selectNode(contentToCopy);
window.getSelection().addRange(range);
// document.execCommand('copy');
await navigator.clipboard.writeText(contentToCopy);
window.getSelection().removeAllRanges();

I’m not sure what to pass into the writeText method.

  1. If I pass contentToCopy.innerText I don’t get the anchor + image
  2. If I pass contentToCopy.innerHTML the HTML is escaped when I paste it into outlook.
  3. If I pass contentToCopy.textContent I get a bunch of weird spacing and no html (expected this)

When I trigger a copy myself (Cmd + C) and paste the result into Outlook, it works fine. How can I mirror that data with JS?

Additionally, I’ve seen this question and answer that says

“instruct the browser to pass the text in as text/html when the copy event fires.”

However, I’m not sure how to accomplish this with the clipboard API.


If it helps, The contentToCopy in this case is a a div with a nested html table

<div id='contentToCopy'>
<table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px;" cellpadding="0" cellspacing="0">
                <tbody style="border:0;">
                    <tr style="border:0;">
                        <td rowspan="6" style="border:0; padding-right:20px;">
                            <a href="https://www.choctawnation.com">
                                <img src="https://associates.choctawnation.com/wp-content/themes/bootscore-main/img/logo.png" width="170px" />
                            </a>
                        </td>
                        <td colspan="5" style="border:0;"><span style="border:0;" id="firstNameOutput">First Name</span> <span style="border:0;" id="lastNameOutput">Last
                                Name</span>
                        </td>
                    </tr>
                    <tr style="border:0;">
                        <td colspan="5" style="border:0;"><span style="border:0;" id="titleOutput">Job
                                Position</span> | <span id="departmentOutput" style="border:0;">Department</span>
                        </td>
                    </tr>
                    <tr style="border:0;">
                        <td colspan="5" style="border:0;">
                            <a href="tel:800-522-6170" id="mobileOutput">
                                <span style="border:0;">
                                    800-522-6170
                                </span>
                            </a>
                            <span id="mobileDivider" style="display: none;">|</span>
                            <a href="" id="desktopOutput">
                            </a>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="5" style="border:0;">
                            <a id="emailOutput" href="mailto:[email protected]"><span style="border:0;">[email protected]</span>
                            </a>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px; padding-top:10px;" cellpadding="0" cellspacing="0">
                <tr>
                    <td rowspan="6" style="border:0;">
                        <a id="buttonOutput"><span style="border:0;"></span>
                        </a>
                    </td>
                </tr>
            </table>
            <table style="text-align: left; font-size: 14px; border:0; border-collapse: collapse; line-height: 25px; padding-top:10px;" cellpadding="0" cellspacing="0">
                <tbody id="disclaimerOutput" class="disclaimerText">
                </tbody>
            </table>
</div>

js how to use dynamic ID from php array in js script

I search directories and I have folder names (about 30). I display them as links, but I would like to have a folder icon in front of each folder name. When I click on folder A, for example, icon1 should change to icon2. When I click on folder A again, icon2 should return to icon1. During this time, the icons of other folders do not change (after one click always I have: 1 icon2 and 29 icon1). For example, when the icon next to the folder A is icon2 and I click on folder B, the icon next to folder A will change (come back) to icon1 and the icon next to folder B will change from icon1 to icon2. The icon and its folder are a one button together.

My script is working with static ID (id=”myB”) of link but with dynamic (from array – $file) not. I tried to use a variable from php to enter the value in js but everything blocked.

this is working script for one link

    <A href="test.php" target="main" id="myB"><img id="myImg" src="folder.png"> folder name </a><BR>
    
<script>
    
    // JavaScript code
    const myB = "myB";
    const myImg = document.getElementById("myImg");
    const myButton = document.getElementById("myB");
    
    myButton.addEventListener("click", function() {
      if (myImg.src.endsWith("folder.png")) {
        myImg.src = "folder_open.png";
      } else {
        myImg.src = "folder.png";
      }
    });
    
    </script>

my dynamic names of folders and dynamic links

foreach ($file_info_all as $file){

   echo ' &nbsp;  <A href="index-main.php?cat=' . $file . '" target="main" id="myB"><img id="myImg" src="folder.png"> &nbsp; ' . $file . '</A><br>';
   
    }

Google maps API not working from Safari 2023

a request from chrome is working perfectly while I get this on Safari, with nothing changing, just the browser. The site is running on https entirely. Changed from fetch to axios with the same results. The key has a restriction on IP.

{
  "data": {
    "error_message": "This IP, site or mobile application is not authorized to use this API key. Request received from IP address XX.XX.XX.XX, with referer: https://XXXX/",
    "results": [],
    "status": "REQUEST_DENIED"
  },
  "status": 200,
  "statusText": "",
  "headers": {
    "cache-control": "no-cache, must-revalidate",
    "content-length": "214",
    "content-type": "application/json; charset=UTF-8",
    "expires": "Fri, 01 Jan 1990 00:00:00 GMT",
    "pragma": "no-cache"
  },
  "config": {
    "transitional": {
      "silentJSONParsing": true,
      "forcedJSONParsing": true,
      "clarifyTimeoutError": false
    },
    "adapter": [
      "xhr",
      "http"
    ],
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "env": {},
    "headers": {
      "Accept": "application/json, text/plain, */*"
    },
    "method": "get",
    "url": "https://maps.googleapis.com/maps/api/geocode/json?latlng=XX.790558469393645,-XX.60082901146109&key=XXXX"
  },
  "request": {}
}

Is it possible to target/run a specific js function through Docker or command line in general?

I am in the process of moving some code functionality inside a AWS batch job which I need to manually run to test before deploying. The handler function inside the js file currently is not targeted and so does not run – (when using a lambda, this function was targeted and ran each time).

Currently I do not want to change the js file to manually run the function each time, rather change the command to somehow target the function – not sure if this is even possible.

This is the command to run the file inside Batch/Docker:

CMD ["node","index.js"]

This is the function def inside the js file:

async function main(event, context)

Any recommendations would be appreciated!

Firestore Connection Issues and Unverified App Check Requests in Firebase Web App

Problem:
I’m experiencing consistent issues with Firebase Firestore in my web application. Although authentication processes succeed (users are created in Firebase Auth), attempts to write to Firestore consistently fail with the following errors:

[Warning] Firestore (10.7.0): Connection - "WebChannel transport errored:" – ir {...}
[Error] Firestore (10.7.0): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: The operation could not be completed...
[Error] Error checking referral code uniqueness: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...
[Error] Error in signup process: – FirebaseError: [code=unavailable]: Failed to get document because the client is offline...

I’m not sure why the client would be offline.

Additionally, I’m encountering CORS-related errors, but this only happened while I was typing this up and I’m not sure what happened:

[Error] Cancelled load to https://www.gstatic.com/recaptcha/releases/.../styles__ltr.css because it violates the resource's Cross-Origin-Resource-Policy response header.

I’m not sure what triggered that either, because I don’t have anything related to recaptcha in my code anywhere except for my site key and the script tags for app check.

Context and Troubleshooting Steps:

  1. This issue started occurring after attempting to implement Firebase App Check and reCAPTCHA, along with updating Firebase SDK from 9.6.10 to 10.7.0 and using modules instead of the global namespace. I reverted to using Firebase 9.6.10 and the global namespace instead of the modular approach, but the issue persists. I then updated back to 10.7.0 while using the global namespace and the issue still persists.

  2. App Check is set up in the Firebase console but not enforced. It showed all requests as unverified, then as verified, back to unverified, and then back to verified without any changes on my side.

  3. In reCAPTCHA, the requests are not marked as suspicious. But for some reason, requests are not being detected there anymore, it was jut requests from yesterday before I was really keeping track of what was going on.

  4. I thought CORS might be an issue, but there were no CORS issues before implementing App Check and reCAPTCHA.

  5. The issue occurs both on localhost and my deployed domain. Both are defined in Firebase and reCAPTCHA.

  6. Firebase Firestore rules have not been altered since the implementation was working correctly.

  7. Tested on different Wi-Fi networks and in incognito mode in a different browser.

  8. I also thought that maybe lite server wasn’t able to handle it, so I moved to Vite and the errors are still happening in my dev environment.

  9. I have verified all my keys and stuff are correct

Firebase Configuration:
Here’s how I’m initializing Firebase in my web app:

const firebaseConfig = {
  apiKey: "mykey",
  authDomain: "myauthdomain",
  projectId: "myprojectID",
  storageBucket: "mystoragebucket",
  messagingSenderId: "mysenderID",
  appId: "myappid",
  measurementId: "mymeasurementID"
};

firebase.initializeApp(firebaseConfig);
firebase.appCheck().activate('mysitekey', true);

HTML Script Tags:

<script src="https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js" defer></script>
<!-- Additional Firebase service scripts -->
<script src="scripts/firebase.js" defer></script>
<!-- Additional custom scripts -->

Code Causing Errors:
The following script triggers functions that throw errors related to Firestore:

function createUserAccount(email, password, referralCode = "") {
    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then((userCredential) => {
            console.log("User created with Firebase Auth, User ID:", userCredential.user.uid);
            const userId = userCredential.user.uid;

            return createUniqueReferralCode().then(newReferralCode => {
                console.log("Generated Unique Referral Code:", newReferralCode);

                // Create a user document in 'users' collection
                const userRef = firebase.firestore().doc('users/' + userId);
                userRef.set({
                    email: email,
                    referralsCount: 0
                });

                // Create a document in 'referralCodes' collection
                return firebase.firestore().collection('referralCodes').doc(newReferralCode).set({
                    ownerId: userId
                });
            });
        })
        .then(() => {
            // Call Cloud Function to update the referrer count
            if (referralCode) {
                return updateReferrerCountCloudFunction(referralCode);
            }
        })
        .then(() => {
            console.log("Redirecting to index.html");
            window.location.href = 'index.html'; // Redirect on successful signup
        })
        .catch((error) => {
            console.error("Error in signup process: ", error);
            document.getElementById('signup-error').innerText = error.message;
        });
}

Observations:
Users are consistently created in Firebase Auth.
Firestore document creation fails every time.
Test signups authenticate users but fail to create documents in Firestore.
Reverting back to the commit before this all started happening still has the issue.
There was a time when instead of failing immediately, it just timed out after 10 seconds. I don’t know what I did to make that happen though, and it hasn’t happened again.

Any insight is appreciated.