GET http://localhost:8080/null 404 (Not Found) in RaspberryPI

Im using RaspberryPI and USB camera to make mini raspberry pi project, but when click start Camera button in web, I got GET http://localhost:8080/null 404 (Not Found) error. Here are codes from my project, but I think one of delivery.html, mqttio.js, mqtt.py is wrong. I’ve really been looking at the code for over 6 hours, but I really don’t know how to fix this. What should I do?

templates/delivery.html

<!DOCTYPE html>
<html>
<head>
        <meta charset="utf-8">
    <title>mini project</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.min.js" type="text/javascript"></script>
    <script src="./static/mqttio.js" type="text/javascript"></script>
    <script src="./static/image.js" type="text/javascript"></script>
    <script>
           window.addEventListener("load", function () {   
                var url = new String(document.location);
                ip = (url.split("//"))[1]; // ip = "224...:8080/"
                ip = (ip.split(":"))[0]; // ip = "224..."
                document.getElementById("broker").value = ip
           });
      </script>
    <style>
        canvas {background-color:lightblue}
    </style>
</head>
<body>
        <h3>camera</h3>
        <hr>
                <form id="connection-form">
                        <b>broker IP:</b>
                        <input id="broker" type="text" name="broker" value=""><br>
                        <b>port : 9001</b><br>
                        <input type="button" onclick="startConnect()" value="Connect">
                        <input type="button" onclick="startDisconnect()" value="Disconnect">
                </form>
        <hr>
    <h3>get image(topic:image)</h3>
         <hr>
         <form id="subscribe-form">
            <input type="button" onclick="startCamera()" value="start camera">
            <input type="button" onclick="stopCamera()" value="stop camera">
         </form>
         <canvas id="myCanvas" width="320" height="240"></canvas>
         <hr>
         <h3>Led (topic:led)</h3>
         <hr>
         <form id="LED-control-form">
            <label>on <input type="radio" name="led" value="1" onchange="publish('led', this.value)"></label>
            <label>off <input type="radio" name="led" value="0" checked onchange="publish('led', this.value)"><br><br></label>
         </form>
         <hr>
         <h3>get temperature(topic:temperature)</h3>
         <hr>
         <form id="subscribe-form">
            <input type="button" onclick="subscribe('temperature')" value="start">
            <input type="button" onclick="unsubscribe('temperature')" value="stop">
         </form>
         <h3>get distance(topic:ultrasonic)</h3>
         <hr>
         <form id="subscribe-form">
            <input type="button" onclick="subscribe('ultrasonic')" value="start">
            <input type="button" onclick="unsubscribe('ultrasonic')" value="stop">
         </form>
         <div id="messages"></div>
</body>
</html>

static/mqttio.js

var port = 9001
var client = null;

function startConnect() {
    clientID = "clientID-" + parseInt(Math.random() * 100);


    broker = document.getElementById("broker").value;

    client = new Paho.MQTT.Client(broker, Number(port), clientID);

    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;
    client.connect({
        onSuccess: onConnect,
    });
}

var isConnected = false;

function onConnect() {
    isConnected = true;
    document.getElementById("messages").innerHTML += '<span>Connected</span><br/>';
}
var topicSave;
function subscribe(topic) {
    if(client == null) return;
    if(isConnected != true) {
        topicSave = topic;
        window.setTimeout("subscribe(topicSave)", 500);
        return
    }

    document.getElementById("messages").innerHTML += '<span>Subscribing to: ' + topic + '</span><br/>';
    client.subscribe(topic);
}

function publish(topic, msg) {
    if(client == null) return;
    client.send(topic, msg, 0, false);
}
function unsubscribe(topic) {
    if(client == null || isConnected != true) return;

    document.getElementById("messages").innerHTML += '<span>Unsubscribing to: ' + topic + '</span><br/>';

    client.unsubscribe(topic, null);
}

function onConnectionLost(responseObject) {
    document.getElementById("messages").innerHTML += '<span>error</span><br/>';
    if (responseObject.errorCode !== 0) {
        document.getElementById("messages").innerHTML += '<span>error : ' + + responseObject.errorMessage + '</span><br/>';
    }
}


function onMessageArrived(msg) {
    console.log("onMessageArrived: " + msg.payloadString);

    if(msg.destinationName == "image") {
        console.log("received")
        drawImage(msg.payloadBytes);
    }

    document.getElementById("messages").innerHTML += '<span>topic : ' + msg.destinationName + '  | ' + msg.payloadString + '</span><br/>';
}

function startDisconnect() {
    client.disconnect(); 
    document.getElementById("messages").innerHTML += '<span>Disconnected</span><br/>';
}

mqtt.py

import io, time
import cv2
from PIL import Image, ImageFilter
import paho.mqtt.client as mqtt
import camera
import base64
import temp
import circuit



isStart  = False

def on_connect(client, userdata, msg, rc):
        client.subscribe("camera")

def on_message(client, userdata, msg):
        global isStart
        if msg.payload.decode('utf-8') == 'start':
                isStart = True
                print("Start Camera")
        else:
                isStart = False
        pass

def on_connect(client, userdata, flag, rc):
    client.subscribe("led", qos=0) 

def on_message(client, userdata, msg):
    on_off = int(msg.payload) 
    circuit.controlLED(on_off) 

broker_ip = "localhost"

client = mqtt.Client()
client.connect(broker_ip, 1883)
client.on_connect = on_connect
client.on_message = on_message

client.loop_start()


camera.init()
stream = io.BytesIO()

while True:
    if isStart == True:
        frame = camera.take_picture()
        stream.seek(0)
        image = Image.fromarray(frame)
        image.save(stream, format='JPEG')
        client.publish("image", stream.getvalue(), qos=0)
        stream.truncate()
    else:
        print("I am idle")
        time.sleep(1)

    distance = circuit.measure_distance()
    temperature = temp.get_temperature(temp.sensor)
    client.publish("ultrasonic", distance, qos=0)
    client.publish("temperature", temperature, qos=0)
    time.sleep(1)

camera.release()

app.py

from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT']=0

@app.route('/')
def index():
        return render_template('delivery.html')

if __name__ == "__main__":
        app.run(host='0.0.0.0', port=8080, debug=True)

circuitpy

import time
import RPi.GPIO as GPIO

def controlLED(on_off):
    GPIO.output(led, on_off)

def measure_distance():
    GPIO.output(trig, 1) 
    GPIO.output(trig, 0) 

    while(GPIO.input(echo) == 0):
        pass

    pulse_start = time.time()
    while(GPIO.input(echo) == 1):
        pass
    
    pulse_end = time.time() 
    pulse_duration = pulse_end - pulse_start 
    return pulse_duration*340*100/2 

trig = 20 # GPIO20
echo = 16 # GPIO16
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(trig, GPIO.OUT) 
GPIO.setup(echo, GPIO.IN) 

led = 6 # GPIO6
led = 5
GPIO.setup(led, GPIO.OUT) # GPIO6 
GPIO.setup(led, GPIO.OUT) # GPIO5 

temp.py

import time
import RPi.GPIO as GPIO
from adafruit_htu21d import HTU21D
import busio

def get_temperature(sensor):
    return float(sensor.temperature)

def get_humidity(sensor):
    return float(sensor.relative_humidity)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sda = 2
scl = 3

i2c = busio.I2C(scl, sda)
sensor = HTU21D(i2c)

def read_sensor_data():
    while True:
        temperature = get_temperature(sensor)
        humidity = get_humidity(sensor)
        print("temperature is %4.1f" % temperature)
        print("humidity is %4.1f %%" % humidity)
        time.sleep(1)

if __name__ == '__main__':
    read_sensor_data()

camera.py

import sys
import time
import cv2
camera = None
def init(camera_id=0, width=640, height=480, buffer_size=1):
    global camera
    camera = cv2.VideoCapture(camera_id, cv2.CAP_V4L)
    camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    camera.set(cv2.CAP_PROP_BUFFERSIZE, buffer_size)

def take_picture(most_recent=False):
    global camera
    len = 0 if most_recent == False else camera.get(cv2.CAP_PROP_BUFFERSIZE)
    while(len > 0):
        camera.grab()
        len -= 1
    success, image = camera.read()
    if not success:
        return None
        
    return image
def final():
    if camera != None:
        camera.release()
    camera = None

static/image.js

var canvas;
var context;
var img;


window.addEventListener("load", function() {
        canvas = document.getElementById("myCanvas");
        context = canvas.getContext("2d");

        img = new Image();
        img.onload = function () {
                context.drawImage(img, 0, 0, canvas.width, canvas.height);
        }
});

function bytes2base64( bytes ) {
    var binary = '';
    var bytes = new Uint8Array( bytes );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

function drawImage(bytes) {
        img.src = "data:image/jpg;base64," + bytes2base64(bytes);
}

var isImageSubscribed = false;
function startCamera() {
        if(!isImageSubscribed) {
                subscribe('image');
                isImageSubscribed = true;
        }
        publish('camera', 'start');
        img.src = null
}
function stopCamera() {
        if(!isImageSubscribed) {
                unsubscribe('image');
                isImageSubscribed = true;
        }
        publish('camera', 'stop');
}

The code using led, ultrasonic sensor, and temperature sensor works fine, but only USB camera is a problem, so I looked at all the related codes, but I couldn’t find any answers.

How to pull data out of Async Fetch function

This seems like it should be very simple and basic, but I’m unable to get data out of an Async fetch function. Below is my code. Any insight into what I might be doing wrong is much appreciated.

const getData = async(url)=>{
    try{
      const response = await fetch(url);
      const data = await response.json();
      console.log(data) //<-- this is working
      return data;
    }
    catch (error){
      console.log(error);
    }
}

const desiredData = getData(url);
console.log(desiredData) // <--this is empty

Connecting Node.js to Redis within docker “Error: The client is closed”

docker-compose.yml has something like this:

version : "3"
services:
  irbredis:
    image: redis:7.2.2-alpine
    container_name: irbredis
  irbserver:
    image: node:20.9.0-alpine
    container_name: irbserver
    depends_on:
      - irbredis

and somewhere in the node.js container, I got this:

const redis = require('redis');
const rclient = redis.createClient({ url: "redis://irbredis:6379" });

The redis server is definitely running, I can expose port from docker-compose and go to URL to check besides logs. But from node.js codes, I get error log:


irbserver  | Error: The client is closed
irbserver  |     at Commander._RedisClient_sendCommand (/app/node_modules/@redis/client/dist/lib/client/index.js:494:31)
irbserver  |     at Commander.commandsExecutor (/app/node_modules/@redis/client/dist/lib/client/index.js:189:154)
irbserver  |     at BaseClass.<computed> [as get] (/app/node_modules/@redis/client/dist/lib/commander.js:8:29)
irbserver  |     at Object.get (/app/node_modules/connect-redis/dist/cjs/index.js:20:34)
irbserver  |     at RedisStore.get (/app/node_modules/connect-redis/dist/cjs/index.js:53:42)
irbserver  |     at session (/app/node_modules/express-session/index.js:485:11)
irbserver  |     at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
irbserver  |     at trim_prefix (/app/node_modules/express/lib/router/index.js:328:13)
irbserver  |     at /app/node_modules/express/lib/router/index.js:286:9
irbserver  |     at Function.process_params (/app/node_modules/express/lib/router/index.js:346:12)

What am I doing wrong?

JWT not seen in the frontend

I’m trying to get my JWT after registring and logging in, but I can only see the JWT token in Postman. In the browser console, I always got undefined.

The token is created after registring with a new user or logging in with an existing one.
That token is erased after logging out.

Registration in the frontend is done with RTK Query

All the NodeJS code is in module style (ES6)

Here’s the code:

UserSchema:

// Imports

const UserSchema = new mongoose.Schema({

  name: {
    type: String,
    required: [true, "Please add a username"],
    unique: true
  },
  email: {
    type: String,
    lowercase: true,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: [8, "Password must contain at least 8 characters"]
  }
};

UserSchema.methods.getJwtToken = function(){ // JWT token
  return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_TIME
  });
})

export default mongoose.model("User", UserSchema);

JWT Options:

export default (user, statusCode, res) =>{
  const token = user.getJwtToken(); // Create JWT Token for the user

  const options = {
    expires: new Date(Date.now() + process.env.COOKIE_EXPIRATION_TIME * 24 * 60 * 60 * 1000),
    httpOnly: true
  }
  res.status(statusCode)
  .cookie("token", token, options)
  .json({ user, token });
}

Register:

import asyncHandler from "express-async-handler";

export const regUser = asyncHandler(async(req, res, next) =>{
  const { name, email, password } = req.body;
  
  const user = await User.create({
    name,
    email,
    password,
  });
  sendToken(user, 201, res);
});

Frontend Code

Registration:

// Imports

const Register = () =>{
  const [data, setData] = useState({
    name: "",
    email: "",
    password: ""
  });
  const { name, email, password } = data
  
  const navigate = useNavigate();
  
  const theme = useSelector((state) => state.theme);
  const { isAuthenticated } = useSelector((state) => state.user);
  const [regUser, { error }] = useRegUserMutation();

  const dataHandler = (e) =>{
    setData({ ...data, [e.target.name]: e.target.value });
  }

  useEffect(() =>{
    if(isAuthenticated){
      toast.error("You Are Already Logged In.");
      navigate("/");
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isAuthenticated]);

  const handleRegister = (e) =>{
    e.preventDefault();
    const data = { name, email, password }
    regUser(data).then(({ data }) =>{
      if(data){
        toast.success("Welcome New User");
        navigate("/");
      }
    });
  }

  return(
    // Registration Form
  )
}

export default Register;

AuthAPI (Code for authentication)

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

import { userAPI } from "../services/userApi";

export const authAPI = createApi({
  reducerPath: "authAPI",
  baseQuery: fetchBaseQuery({
    baseUrl: "/api/v1"
  }),
  endpoints: (builder) =>({
    regUser: builder.mutation({
      query(body){
        return{
          url: "/register",
          method: "POST",
          body
        }
      },
      async onQueryStarted(args, { dispatch, queryFulfilled }){
        try{
          await queryFulfilled;
          await dispatch(userAPI.endpoints.getCurrentUser.initiate(null)) // Getting the user after a successful registration
        }
        catch(error){
          console.log(error);
        }
      },
    })
  })
});

export const { useRegUserMutation } = authAPI;

Custom error message for response status 404

Why can’t I catch a custom error message after receiving an error with status 404? I expected that in both approaches, the error message would be throwed to the nearest catch block.

version 1:

export const checkMovieExists = async (movieId) => {
  const url = `http://api.themoviedb.org/3/movie/${movieId}?api_key=${TMDB_API_KEY}`;

  const movieExists = await axios
    .get(url)
    .then((res) => {
      if (res.status === 200) {
        return true;
      }
      throw new Error(`Movie with ID ${movieId} not found.`);
    })
    .catch((error) => {
      console.log(error.message);
      return false;
    });

  return movieExists;
};

console output: "Request failed with status code 404"


version 2:

export const checkMovieExists = async (movieId) => {
  const url = `http://api.themoviedb.org/3/movie/${movieId}?api_key=${TMDB_API_KEY}`;

  try {
    const movieExists = await axios.get(url).then((res) => {
      if (res.status === 200) {
        return true;
      }
      throw new Error(`Movie with ID ${movieId} not found.`);
    });
    return movieExists;
  } catch (error) {
    console.log(error.message);
    return false;
  }
};

console output: "Request failed with status code 404"

Double audio on a video after changing its src via javascript. How to destroy the old one?

Please take a look (simplyfied):

function set_video(){
  let width = window.innerWidth;
  let video_source = null;

  if(width < 721){
    video_source = video_sources.small; // video_sources is an array of video urls
  } else {
    video_source = video_sources.large;
  }

  video.src = video_source;
}

set_video();

window.addEventListener('resize', _.debounce(set_video,150));

So, the videos are changing correctly, but when I swap the source, the old video is somewhat not destroyed and continues to play its audio (so I end up with 2 audio playing together). How to avoid this issue? Maybe removing and swapping the entire video tag instead of the src only?

How to resolve the error react native, @expo/webpack-config requires a valid `mode` string which should be one of: development, production, none?

I try to dockerize production mode of react native web.

But I get this error:

> [dwl_frontend build 7/7] RUN yarn run build:
1.037 yarn run v1.22.19
1.099 $ webpack --config webpack.config.js
2.953 [webpack-cli] Error: @expo/webpack-config requires a valid `mode` string which should be one of: development, production, none
2.953     at validateEnvironment (/app/node_modules/@expo/webpack-config/webpack/env/validate.js:23:15)
2.953     at createWebpackConfigAsync (/app/node_modules/@expo/webpack-config/webpack/index.js:23:55)
2.953     at module.exports (/app/webpack.config.js:6:23)
2.953     at loadConfigByPath (/app/node_modules/webpack-cli/lib/webpack-cli.js:1445:37)
2.953     at async Promise.all (index 0)
2.953     at async WebpackCLI.loadConfig (/app/node_modules/webpack-cli/lib/webpack-cli.js:1460:35)
2.953     at async WebpackCLI.createCompiler (/app/node_modules/webpack-cli/lib/webpack-cli.js:1781:22)
2.953     at async WebpackCLI.runWebpack (/app/node_modules/webpack-cli/lib/webpack-cli.js:1877:20)
2.953     at async Command.<anonymous> (/app/node_modules/webpack-cli/lib/webpack-cli.js:944:21)
2.953     at async Command.parseAsync (/app/node_modules/webpack-cli/node_modules/commander/lib/command.js:935:5)
2.973 error Command failed with exit code 2.
2.973 info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
------
failed to solve: process "/bin/sh -c yarn run build" did not complete successfully: exit code: 2

I think this has not to do with docker. But I have webpack.config. js file:

/* eslint-disable prettier/prettier */
const createExpoWebpackConfigAsync = require("@expo/webpack-config");

module.exports = async function (env, argv) {
    const config = await createExpoWebpackConfigAsync(env, argv);

    if (config.mode === "production") {
        config.devServer.compress = false;
    }

    return config;
};

And package.json file:

    "scripts": {
        "start": "expo start, react-app-rewired start ",
        "android": "expo start --android",
        "ios": "expo start --ios",
        "web": "expo start --web",
        "eject": "expo eject",
        "lint": "eslint . --ext .js",
        "postinstall": "patch-package",
        "build": "webpack --config webpack.config.js",
        "start-webpack": "webpack-dev-server --mode production --open"
    },

And this is the dockerfile:


ARG NODE_VERSION=lts


ARG NGINX_VERSION=alpine

FROM node:${NODE_VERSION}-bullseye-slim as deps

WORKDIR /app

ENV NODE_OPTIONS=--openssl-legacy-provider

COPY ./package.json ./yarn.lock ./


RUN yarn set version latest

ARG NODE_ENV
ENV NODE_ENV $NODE_ENV

# Install dependencies
RUN yarn install --frozen-lockfile

# Stage 2: Build
FROM node:${NODE_VERSION}-bullseye-slim as build

WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY ./ ./app
COPY ./assets ./assets
COPY ./package.json ./webpack.config.js  ./App.js ./app.json ./babel.config.js ./


RUN yarn run build  


FROM nginx:${NGINX_VERSION} as run

ARG VERSION=1.0.0
ARG BUILD_DATE

LABEL version="${VERSION}"
LABEL BuildDate="${BUILD_DATE}"


COPY --from=build /app/web-build /usr/share/nginx/html


EXPOSE 80


CMD ["nginx", "-g", "daemon off;"]

But when I do ““ docker compose -f docker-compose-prod.yml build“`

I get the error I mentioned

[webpack-cli] Error: @expo/webpack-config requires a valid `mode` string which should be one of: development, production, none

Question: how to resolve the error?

NextJs Button onClick does not call my implemented function

I created a NextJS project and added a Button inside my Home in my page.tsx
While pressing the button a alert shout occur. The alert is just for the testing, because it does not work…

'use client';
import React from 'react';
import "./page.css"

export default function Home() {

  function handleClick() {
    alert("test");
  }

  return (
    <div className="main-container">
      <h1>//comment my code</h1>
      <textarea placeholder="Please insert your code..." className="main-input" />
      <button type='submit' onClick={handleClick} id='start' >Go!</button>
      <h3 hidden>Detected language:</h3>
      <textarea hidden className="main-language" />
      <h3 hidden>Comment code: </h3>
      <textarea hidden className="main-output" />
    </div>
  )
}

I cannot find the problem. Everything i found, i already tried and did. Do you guys have any ideas, what could be wrong?

I also enabeled js in my browser

Redis connection with express session

I am using redis and express-session for session of user but when i am doing this operation error is coming.

Error: The client is closed
at Commander._RedisClient_sendCommand (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/@redis/client/dist/lib/client/index.js:510:31)
at Commander.commandsExecutor (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/@redis/client/dist/lib/client/index.js:190:154)
at Commander.<computed>.<computed> [as set] (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/@redis/client/dist/lib/commander.js:58:33)
at RedisStackAsyncStore.set (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/connect-redis-stack/dist/index.js:92:28)
at /Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/connect-redis-stack/dist/index.js:48:32
at RedisStackStore.set (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/connect-redis-stack/dist/index.js:53:7)
at Session.save (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/express-session/session/session.js:72:25)
at Session.save (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/express-session/index.js:406:15)
at ServerResponse.end (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/express-session/index.js:335:21)
at ServerResponse.send (/Users/aaryarastogi/MERN_Projects/tourism/backend/node_modules/express/lib/response.js:232:10)

Can anyone help me in solving this issue?

Solve my issue and give me updated code or tell me where i am lacking.
Tell me how to connect redis 4th version with express-session using connect-redis 7th version.

OBJ & MTL Loaders in Three.js

I wanna add my 3D model to three.js scene via OBJ & MTL loaders, but there is an issue in console:
THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The “position” attribute is likely to have NaN values.

There are no any lines in my code like these. There are some NaN values like radius and x y z coordinates, but I also don’t know where it inits.enter image description here

I was comment other parts of code and an issue was still there.
I added console.log after loaders call, its working so issue is unrelated with loaders.
Btw, cubes, spheres and other objects appear at scene, there are no any problems with it.

What is wrong with my app.jsx file? Why cant I pull data from my mongodb atlas cluster?

I am building a website that allows users to search for homes based on the criteria they input into a form (when they click search they are shown a list with matching home results). I have created the form

            <form id="form" role="search">
                <!--<form action="/search" method="get"-->
                <div class="left-column">

                    
                    <label for="beds">Beds:</label>
                    <input type="text" name="beds" id="num-beds" placeholder="1,2,3+">

          
                    <label for="baths">Baths:</label>
                    <input type="text" name="beds" id="num-beds" placeholder="1,2,3+">
                    
                    <label for="acer-lot">Acer lot:</label>
                    <input type="text" name="acer-lot" id="num-beds" placeholder="1,2,3+">
                    
                    <label for="city">City:</label>
                    <input type="text" name="city" id="search-city">
                    
                </div>

                <div class="right-column">

                    <label for="state">State:</label>
                    <input type="text" name="state" id="search-state">

          
                    <label for="zip">Zip Code:</label>
                    <input type="text" name="zip" id="search-zip">
                    
                    <label for="sqft">Square Footage:</label>
                    <input type="text" name="sqft" id="square-foot">
                    
                    <label for="price-range">Price Range:</label>
                    <input type="text" name="price-range" id="price">
                    
                </div>

                </div>-->
                <div class="submit">
                    <button type="search">Search</button>
                </div>

            </form>

added my .csx file (only a snippet shown as their is alot of data) to a mongodb atlas cluster

status,bed,bath,acre_lot,city,state,zip_code,house_size,prev_sold_date,price
for_sale,3,2,0.12,Adjuntas,Puerto Rico,601,920,,105000
for_sale,4,2,0.08,Adjuntas,Puerto Rico,601,1527,,80000
for_sale,2,1,0.15,Juana Diaz,Puerto Rico,795,748,,67000
for_sale,4,2,0.1,Ponce,Puerto Rico,731,1800,,145000
for_sale,6,2,0.05,Mayaguez,Puerto Rico,680,,,65000 

and created an app.jsx file.

const express = require('express');
const MongoClient = require('mongodb').MongoClient;

const app = express();
const port = 3000;

// Replace the URL with your MongoDB connection string
const mongoUrl = 'mongodb://localhost:27017/homesearchsite';

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Serve your HTML form
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// Handle the form submission
app.get('/search', (req, res) => {
  const { beds, baths, acerLot, city, state, zip, sqft, price } = req.query;

  // Create your MongoDB query based on the search criteria
  const query = {
    bed: { $gte: parseInt(beds) },
    bath: { $gte: parseInt(baths) },
    acre_lot: { $gte: parseFloat(acerLot) },
    city: new RegExp(city, 'i'), // Case-insensitive search
    state: new RegExp(state, 'i'),
    zip_code: new RegExp(zip, 'i'),
    house_size: { $gte: parseInt(sqft) },
    price: { $lte: parseInt(price) }
  };

  // Connect to MongoDB and perform the query
  MongoClient.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
    if (err) throw err;

    const db = client.db();

    db.collection('home.search')
      .find(query)
      .toArray((err, results) => {
        if (err) throw err;

        // Return the search results
        res.json(results);

        // Close the MongoDB connection
        client.close();
      });
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

Despite this when I fill out the form and click search I don’t see a result, it basically looks like the page reloaded. How can I adjust my code to make it show me results?

Failed to load module script: Strict MIME type checking is enforced for module scripts per HTML spec

Ive been stuck with this issue for the past 3 days. Ive tried looking into different threads but nothing seems to work for me.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.

Ive tried a couple of things but the issue im running into is with the type=”module” in index.html. When I include it, I run into the error above, and when I remove it, I run into this error Uncaught SyntaxError: Cannot use import statement outside a module. Ive also attempted to change signup.js into signup.mjs. In the import statement, the path seems to be correct with firebase/app/dist/app being inside of node_modules. Ive also seen that the way im hosting might cause an issue. Currently, im using npm start with live-server. Any help is greatly appreciated!

Here is my scripts/signup.js

import { initializeApp } from "/../node_modules/firebase/app/dist/app";

const firebaseConfig = {
// tokens
};

const app = initializeApp(firebaseConfig);

async function signup(event) {
    event.preventDefault();

    const username = document.getElementById('signupUsername').value;
    const password = document.getElementById('signupPassword').value;

    console.log(username, password, generateUUID())
}

My index.html is a bit long, so instead of spamming ill just add the script tag

    <script src="scripts/signup.js" type="module"></script>

package.json

{
  "dependencies": {
    "firebase": "^10.6.0",
    "pg": "^8.11.3",
    "pool": "^0.4.1",
    "type":"module"
  },
  "scripts": {
    "start": "live-server"
  }
}

How do I filter the query based on language in defineArrayMember Sanity

`

import { defineField, defineArrayMember } from "sanity";

export const tools = defineField({
  name: "tools",
  title: "Tools",
  type: "document",
  fields: [
    defineField({
      name: "usp",
      title: "usp",
      type: "array",
      of: [
        defineArrayMember({
          type: "object",
          name: "tag",
          fields: [
            { type: "internationalizedArrayString", name: "label" },
            { type: "internationalizedArrayString", name: "value" },
          ],
        }),
      ],
    }),,
  ],
});

export async function getTools(language) {
  return client.fetch(
    `*[_type == "tools"] {
        usp,
        subTitle[_key == '${language}'],
        subParagraph[_key == '${language}'],
        sideTitle[_key == '${language}'],
        sideParagraph[_key == '${language}']
    }[0]`
  );
}

`

As you might see I am already able to filter the subTitle and other key values based on selected language. Only the thing I need to figure out is how can I apply the language filter to the usp queries?How the current console log looks like. So on the image you see the SideTitle for instance already gets filtered.

I tried to apply the same logic, but there are some nested arrays in there. So what I expect is to not filter in the React component itself, but in the query which makes the code much cleaner and more scalable.

React (typescript) import module from other local library: (module has no exports)

I created a local library and before publish it to npm I want to test it from another projet.

So I created my library with the following tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true
  },
  "include": [
    "src/**/*.tsx"
  ],
  "exclude": ["node_modules", "dist"]
}

And my package.json contains:

  "scripts": {
    "build": "tsc",
    "prepublishOnly": "npm run build"
  },
  "files": [
    "dist",
    "src",
    "README.md"
  ],
  "main": "dist/index.js",
  "types": "dist/index.d.ts"

After building the lib and getting a “dist” directory, I import a file from this lib on another projet:

import {eventProfiler} from "authguard-hiding-spotted/dist/class/Profiler";

The IDE allows the import but when I start my app with this import, I got this error:

Attempted import error: 'eventProfiler' is not exported from 'authguard-hiding-spotted/dist/class/Profiler' (imported as 'eventProfiler').

But why? On my builded file I got this export declare class eventProfiler, so the class is explicitly exported.