maxHeight attribute is seemingly ignored

I am trying to make a simple ‘video chat’ web interface using React and Chakra UI, but i am met with a problem when trying to setup and style my pages.

My layout is very simple:

import React from "react";
import { Flex } from "@chakra-ui/react";
import { LocalVideoElement, RemoteVideoElement } from "../components/VideosHandlerComponent";

export default function VideoChatFlex() {
    return (
        <Flex id='videoContainer' direction='column' align='center' justify='center' maxHeight={"100px"} >
            <LocalVideoElement />
            <RemoteVideoElement />
        </Flex>
    );
}

The video elements are made as such :

export function LocalVideoElement() {

    const streamInfo = GetStreamInfo();

    const [localVideoElement, setLocalVideoElement] = useState<HTMLVideoElement | null>(null);
    useEffect(() => {
        if (localVideoElement && streamInfo.localStream) {
            localVideoElement.srcObject = streamInfo.localStream;
        }
    }, [localVideoElement, streamInfo.localStream]);


    return (
        <video
            id='localVideo'
            ref={(video) => setLocalVideoElement(video)}
            controls={false}
            autoPlay
            playsInline
            muted
        />
    );
}

I’m running into a problem when trying to limit the size of the videos to the page’s height, when the video elements seem to ignore all height limits.

For example, I am setting the maxHeight of my container to 100px , but as soon as the video loads the video element grows to 480 pixels, while the container stays at 100px. The “overflowing” part of the video elements is displayed as a dashed purple element in chrome devtools (available space to expand apparently)

However, if I put the size requirement on the width (maxWidth={"100px"}) then everything is fine and the videos are sized to fit within the container.

Am I missing something here? How can I fix that?

add rubberbanding bounce overscroll on desktop firefox

questions about overscroll usually ask how to disable it on a mobile web page. I want to do the opposite: create a rubber banding effect on all web pages while browsing on the desktop. I’m using either the space bar, page down or mouse wheel to scroll.

I tried html { overscroll-behavior: contain; overflow: scroll } on Firefox. Don’t know what else to do.

Clone and change id of img upload

So out of curiosity and teaching myself how to code I’ve decided to make a twitter mimic. I’ve been doing decently well until now — I’m trying to make it so you can hit the “clone tweet” button and it will clone the base of the tweet, but allow you to change the icon to whatever you like. But, every time I try and upload anything it only changes the very first icon, the “mat” aka make a tweet one. I have no clue how to get this to work properly and would love some help figuring it out.

Here is the coddepen im using:
https://codepen.io/laurenlola/pen/GRLPOyJ?editors=0010

javascript

let c = 0 
function IDgenerate() { 
return c++ 
   } 
$("#clickme").on("click", function() { 
   var cn = IDgenerate(); 
                
     let clone = $("#cloneme").clone() 
     clone.css("display", "inline-block") 
      clone.find('#setID').attr("id", cn) 
       clone.find("#cancel").attr("id", "cancel" + cn) 
                clone.find("#cancel" + cn).on("click", function() { 
                        clone.css("display", "none") 
                    }) 
                $("#bucket").append(clone) 
            }) 

 //imageupload
function showMyImage(fileInput) {
  var files = fileInput.files;
    for (var i = 0; i < files.length; i++) {           
        var file = files[i];
        console.log(file.name);
        var imageType = /image.*/;     
        if (!file.type.match(imageType)) {
            continue;
        }           
        var img=document.getElementById("thumbnil");            
        img.file = file;    
        var reader = new FileReader();
        reader.onload = (function(aImg) { 
            return function(e) { 
                aImg.src = e.target.result; 
            }; 
        })(img);
        reader.readAsDataURL(file);
        thumbnil.style.display = 'block';

    }
  }

HTML

    <div class="matweet"> 
              <div class="avatar-wrapper">
        <div class="upload-button"> 
            <input type='file' id="upload" onchange="showMyImage(this)" class="fa fa-arrow-circle-up"  aria-hidden="true" />
        <img id="thumbnil" src="https://t3.ftcdn.net/jpg/05/08/88/82/360_F_508888212_50sPZWAnDEe0IdZGwd5fb1CUDEFPNJgy.jpg" style="display: block;width: 50px;height: 50px;margin: 0 0 -5px -5px"/></div>
    </div>      
        <input type="text" placeholder="What is happening?!"></div>

        <div class="maticons">
                    <i class="fa-regular fa-image" style="color: #1d9bf0;"></i>&emsp;&nbsp;
                    <i class="fa-regular fa-box" style="color: #1d9bf0;"></i>&emsp;&nbsp;
                    <i class="fa-solid fa-list" style="color: #1d9bf0;"></i>&emsp;&nbsp;
                    <i class="fa-regular fa-smile"  style="color: #1d9bf0;"></i>&emsp;&nbsp;
                    <i class="fa-regular fa-calendar"  style="color: #1d9bf0;"></i>&emsp;&nbsp;
                    <i class="fa-solid fa-location-dot"  style="color: #1d9bf0;"></i>
                    
                    <button class="button button1">
                    Post
                    </button>
        </div>     
                    
        </div>
  <!---- Avatar upload end-->
        <div id="cloneme">
        <div class="tweet">
            <div class="twticon">
     <div class="avatar">
        <div class="upload-button">  
            <input type='file' id="upload" onchange="showMyImage(this)" class="fa fa-arrow-circle-up"  aria-hidden="true" />
        <img class="thumbnil"  id="setID" src="https://t3.ftcdn.net/jpg/05/08/88/82/360_F_508888212_50sPZWAnDEe0IdZGwd5fb1CUDEFPNJgy.jpg" alt="logo" style="display: block;width: 50px;height: 50px;margin: -5px"/></div>
    </div>
    </div>  
            <b><div class="username" contentEditable="true">Usernames</b>&emsp;<text style="color:gray">@username</text></div><br>
        <div class="tweetst" contentEditable="true"> Testing Testing Testing Testing Testing Testing Testing Testing Testing Testing Testing Testing Testing
        <p></div>
        <div class="tweeticons">
        
        <i class="fa-solid fa-comment"  style="color:gray">&thinsp;</i><b div  style="color:gray" contentEditable="true" >24K</b>&emsp;&emsp;&emsp;
        <i class="fa-solid fa-undo"  style="color:gray">&thinsp;</i><b div  style="color:gray" contentEditable="true">754K</b></i>&emsp;&emsp;&emsp;
        <i class="fa-solid fa-heart"  style="color:gray">&thinsp;</i><b div  style="color:gray" contentEditable="true">9.1K</b></i>&emsp;&emsp;&emsp;
        <i class="fa-solid fa-bar-chart" style="color:gray">&thinsp;</i><b div  style="color:gray" contentEditable="true" maxlength="4">257K</b> &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&thinsp;&thinsp;&thinsp;
        <i class="fa-solid fa-bookmark"  style="color:gray">&thinsp;</i>
        </div>
</div>
</div>

    <div id="bucket" class="container-fluid"> 

</div>

<button type="button" class="btn btn-success" id="clickme" >Clone Tweet</button> 

And again, thanks soooo much for any help.

I’ve tried a couple different ways to cline and change the id but im just not sure how to connect it all together to change properly when hitting the clone button

How to change css style of element inside iframe using css and javascript?

I inserted this calculator: service-online.su/text/calc/calc1-01.php into my website in iframe tag:

<iframe id="myIframe" src="//service-online.su/text/calc/calc1-01.php" scrolling="no" height="370px" width="650px" frameborder="0" marginheight="0" marginwidth="0"></iframe>

But when I click on Compute (“посчитать”) button 2 or more times, inputs above this button duplicate.

I tried to style by id, class, but no result.
How can I fix this bug?
I have no access to the code of service-online.su/text/calc/calc1-01.php.
Please help!

react useEffect handleKeyDown dubbleing output with every entry

every input results in doubble the amount of outputs each time resulting in getting stuck in a long loop after just a few inputs.
this is the code

  const [direction,setDirection] = useState(Array(1).fill(0));
  const directions = ["botNorth","botEast","botSouth","botWest"];
  const [squares, setSquares] = useState(Array(5).fill().map(()=> Array(5).fill(null)));

  useEffect(()=> {
    const handleKeyDown = (e) =>{
      e = e || window.event;
      const nextSquares = squares.slice();
      var nextDirection = direction.slice();
      console.log(e.which);
      if (e.keyCode == '38') {
          // up arrow
      }
      else if (e.keyCode == '37') {
         // left arrow
         nextDirection[0]--;
         if (nextDirection[0] < 0) {
          nextDirection[0] = 3;
         }

      }
      else if (e.keyCode == '39') {
         // right arrow
      }
      setDirection(nextDirection);
      nextSquares[location[0]][location[1]] = <img className={directions[nextDirection[0]]} src={bot}/>;
      setSquares(nextSquares);
    return () => document.removeEventListener('keydown', handleKeyDown);
    };
    document.addEventListener('keydown', handleKeyDown, true);
});

this is the resulting error each key was only pressed once
screenshot of error

I’ve tryed moving the the add and remvove listeners around both inside and outside the function but it doesnt seem to make a difference
when i comment out both setSquare() and setDirection() it outputs twice per input instead of doubbleing each time

Discord API: Give members access to existing private channel

I am working on a feature in my Next.js app to add permission to new members access to specific private channels. I found a solution here but did not work in my application. I had given my bot essentially all the bot permission in general permission, as well as application.commands permission.

Whenever I call my api endpoint, however, it returns

Error updating channel permissions: { message: 'Missing Access', code: 50001 }

This is my current implementation below, an api call that takes in a user id and the channel id to which the user should have access to. Any help is appreciated.

import axios from "axios"

export default async function handler(req, res) {
  const { channelId, userId } = req.body
  const botToken = process.env.DISCORD_BOT_TOKEN

  try {
    const permissions = 0x400 | 0x800

    const response = await axios.put(
      `https://discord.com/api/v9/channels/${channelId}/permissions/${userId}`,
      {
        allow: permissions.toString(), // Convert numeric permission to string if needed
        deny: "0", // Specify no permissions are denied as a string
        type: 1, // Member type
      },
      {
        headers: {
          Authorization: `Bot ${botToken}`,
          "Content-Type": "application/json",
        },
      }
    )

    return res.status(200).json({
      success: true,
      message: "Permissions updated successfully",
      data: response.data,
    })
  } catch (error) {
    console.error(
      "Error updating channel permissions:",
      error.response ? error.response.data : error.message
    )
    return res.status(500).json({
      success: false,
      message: "Failed to update channel permissions",
      error: error.response ? error.response.data : { message: error.message },
    })
  }
}

How to create a plugin website without Google Extencions?

I am looking for a way to program a type of .exe executable that when opened is activated so that when entering a specific web page it inserts the code that I want to change the layout or implement some functionality. This can easily be done by programming something like a Google extension, but what I’m looking for is to do it a little more locally using an exe. What suggestions do you have for me or what I could research to come up with something like this?

I tried to use google extencions

Set a variable from a json file and get a second API json

I’m a total newb when it comes to javascript and json. As it will soon show. I had some experience with javascript back 12 or so years ago. But it was minimal. So, go easy on me.

It’s difficult to explain exactly what the issue is that I am having. So, I’ll make an example here. I have an API url that I need to get another API URL from and then use that json file to create my html page. I can fetch the first json file just fine at, lets say, http://www.thiscarsite.com/API/thecars And it’s set up similar to the following example.

{ "manufacturer": "Cheverolet",
  "model": "Camaro",
  "year": "1990",
  "styles": {
        "top": "convertible",
        "engine"; "v8",
        "address": "http://www.somesite.com/api/90ChevCamConvV8"
        }
}

As I said, I can get the first json information just fine with fetch/await. Or something as simple as this.

const startUrl = 'http://www.thiscarsite.com/API/thecars';
fetch(startUrl)
  .then(response => {
    return response.json();
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

I have seen examples where one gets the URL by const newURL = data.styles.address; But how do I go about getting the address from the example above AND requesting the 2nd json file? I failed to mention that the URL in the first json file can change 3 or 4 times per week. Thus, the need to get it from the first one every time I need to access it.

I know this information is probably easy to find. I’m just not smart enough on the subject to be able to use the proper search terms.

I appreciate anyone taking the time to point me in the right direction.

WHAT I TRIED, With No luck

Tried something like this, my edits to insert the 2nd URL resulted in a failure

fetch('https://example.com/endpoint1')
  .then(response => {
    return response.json();
  })
  .then(data1 => {
    return fetch(`https://example.com/endpoint2?data=${data1}`);
  })
  .then(response => {
    return response.json();
  })
  .then(data2 => {
    console.log(data2);
  })
  .catch(error => {
    console.error(error);
  });

Also, tried using 2 async functions but kept getting errors like “response already called” (or something to the effect)

Flask and JS error: Uncaught SyntaxError: Unexpected token ‘<'

This part of the Flask webapp is attempting to read data from a database table and present it in HTML format using a Javascript file that performs this operation and is called upon loading the HTML site all enclosed into a single Flask app.

I’ve tried moving the JS script into the HTML file itself but getting the same error as if calling the JS file.

The error I see in the Browser Console are two:

Uncaught SyntaxError: Unexpected token '<' (at VM214 tabTables.js:1:1) VM214 tabTables.js:1

Uncaught SyntaxError: Unexpected token '<' (at tabTables.js:1:1) tabTables.js:1

My HTML code where the JS script is called from is this one:


{% block content %}
<h2>{% block title %}Admin{% endblock %}</h2>
<div class="admin-container">
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="user-tab" data-toggle="tab" href="#user" role="tab" aria-controls="user" aria-selected="true">User List</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="product-tab" data-toggle="tab" href="#product" role="tab" aria-controls="product" aria-selected="false">Product List</a>
        </li>
    </ul>
    <div class="tab-content" id="myTabContent">
        <div class="tab-pane fade show active" id="user" role="tabpanel" aria-labelledby="user-tab">
            <table id="user-table" class="table">
                <!-- User list table content will be loaded here dynamically -->
            </table>
        </div>
        <div class="tab-pane fade" id="product" role="tabpanel" aria-labelledby="product-tab">
            <table id="product-table" class="table">
                <!-- Product list table content will be loaded here dynamically -->
            </table>
        </div>
    </div>
</div>
{% block javascript %}
<!-- Include JavaScript file specific to the admin page -->
<script src="{{ url_for('static', filename='tabTables.js') }}"></script>
{% endblock %}
{% endblock %}

My Javascript Code called from the HTML is this one:

<script>
    // Function to load user or product list based on active tab
    function loadList(tabId, tableName) {
        $.ajax({
            url: '/load_list',
            method: 'POST',
            data: { table: tableName },
            success: function(response) {
                console.log('Response received:', response); // Log the response
                if (response.trim() === '') {
                    // Display a message indicating that the table is empty
                    $(tabId).html('<p>No data available.</p>');
                } else {
                    $(tabId).html(response);
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error); // Log the error
                // Display an error message
                $(tabId).html('<p>Error loading data.</p>');
            }
        });
    }

    // Event listener for tab switching
    $('#myTab a').on('shown.bs.tab', function (e) {
        var tabId = $(e.target).attr('href');
        var tableName = $(e.target).attr('data-table');
        loadList(tabId + '-table', tableName);
    });

    // Load user list initially
    loadList('#user-table', 'users');
</script>

the flask app section with the route to that HTML page is this one:

# Route for the admin page
@app.route('/admin')
def admin():
    return render_template('admin.html')

I’ve read through lots of posts but couldn’t find much related to this issue; main piece of feedback I’ve read is:

The error Uncaught SyntaxError: Unexpected token ‘<‘ typically indicates that the browser is trying to parse HTML as JavaScript. This usually occurs when the JavaScript file being loaded contains HTML content instead of valid JavaScript code.

Still I was not able to find a way for the browser to show that there is no data in the table, which is empty but should resolve the below message per JS if statement:

if (response.trim() === '') {
                    // Display a message indicating that the table is empty
                    $(tabId).html('<p>No data available.</p>')

I’d appreciate any guidance on what I can do to keep debugging this.

What really is a function expression? [duplicate]

Can someone explain me please if a function expression involves the function value along the variable in where it’s stored or is really only the function value?, so i always see that the “function expression” term points to this whole snippet:

const funcExp = function(){console.log("Hello World!")};

But i was wondering.. then what about this:

function(){console.log("Hello World!")}

if you ask me i would say that the function expression is only the function value itself, which basically would be a pure anonymous function, no? i could be wrong but.. do you really don’t think that would be strange to call this an anonymous function?:

const funcExp = function(){console.log("Hello World!")};

i mean in some way already has a name, not directly as part of the function value, but as part of the variable in where its stored, so i don’t know i just want to know what really is a function expression, the whole variable creation initialized with a function value or only that function value, if the first turns to be true then how do we call this type of function values function(){console.log("Hello World!")}? function expression also?; thanks.

How can i delete table row from database?

list.js file

delete icon:

td = document.createElement("td");          
          td.setAttribute("style","border: 1px solid black;");          
          cellText = document.createElement('i'); 
          cellText.setAttribute("data-id",data[i].pid);         
          cellText.setAttribute("class","fa-solid fa-trash");
          cellText.setAttribute("onclick", "pDelete(this)");
          td.appendChild(cellText);          
          row.appendChild(td);     

pDelete(elem):

pDelete(elem) {
        let id = elem.getAttribute("data-id");
        fetch(`pdelete/index.php?id=${id}`, {
            method: 'DELETE'
        });
    }

pWorks file:

public static function pDelete($params){
        $params=json_encode($params, true);
        extract(json_encode($params,true));
        $db=new DBConnect();
        $sql="DELETE from products  WHERE pid=:$id";
        $db->sqlExec($sql);
    }

pdelete/index.php file:

<?php

require_once("../app/pWorks.php");

if ($_SERVER["REQUEST_METHOD"] == "DELETE") {
    $id = isset($_GET['id']) ? $_GET['id'] : null;
    if (!empty($id)) {
        pWorks::pDelete($id);
        echo "deleted";
    }else{echo "nope";}

}

my primary key is pid on database. it doesnt delete anything.

my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything. my primary key is pid on database. it doesnt delete anything.

three.js – phone scroll model

I am interested in creating this iphone scroll effect in three.js – I’ve seen it on this website
https://www.exo.inc/exo-works

enter image description here

  • but I am unsure/stuck on how to clean up the code to form a sandbox for just that asset. I’ve not seen any examples like this before.

I think this is used https://docs.pmnd.rs/react-three-fiber/getting-started/examples and you can inspect this on the actual scripts used in exo.inc if you look at threejs-notes

My current sandbox – but not been able to get it to render
https://codesandbox.io/p/sandbox/hungry-https-yt78df?file=%2Fsrc%2F3d%2FphoneModel.js

import { useGLTF } from '@react-three/drei';
import { useLayoutEffect, useMemo, useRef } from 'react';
import * as THREE from 'three';
import { MeshBasicMaterial } from 'three';
import { GLTF } from 'three-stdlib';

import { use3dStore } from '~/stores/3d/store';

type PhoneModelProps = {
  groupPos: [number, number, number];
  groupRot: [number, number, number];
  modelScale: number;
  visible: boolean;
  onLoadFn?: () => void;
} & JSX.IntrinsicElements['group'];

type GLTFResult = GLTF & {
  nodes: {
    M_Cameras: THREE.Mesh;
    M_Glass: THREE.Mesh;
    M_Metal_Rough: THREE.Mesh;
    M_Metal_Shiny: THREE.Mesh;
    M_Plastic: THREE.Mesh;
    M_Portal: THREE.Mesh;
    M_Screen: THREE.Mesh;
    M_Speakers: THREE.Mesh;
    M_USB: THREE.Mesh;
  };
  materials: {
    cam: THREE.MeshStandardMaterial;
    ['glass.001']: THREE.MeshStandardMaterial;
    metal_rough: THREE.MeshStandardMaterial;
    metal_Shiny: THREE.MeshStandardMaterial;
    ['M_Base.001']: THREE.MeshStandardMaterial;
    Screen: THREE.MeshStandardMaterial;
  };
};

export function PhoneModel({ groupPos, groupRot, modelScale, visible, onLoadFn }: PhoneModelProps) {
  const { nodes, materials } = useGLTF('/assets/models/Iphone15.glb') as GLTFResult;
  const groupRef = useRef<THREE.Group>(null);
  const modelRef = useRef<THREE.Group>(null);
  const screenRef = useRef<THREE.Mesh>(null);
  const { setPhoneGroupRef, setPhoneModelRef, setPhoneScreenRef } = use3dStore([
    'setPhoneGroupRef',
    'setPhoneModelRef',
    'setPhoneScreenRef',
  ]);

  // Duplicate the screen material so we can modify it without impacting other instances
  const screenMaterial = useMemo(() => {
    const mat: MeshBasicMaterial = new MeshBasicMaterial().copy(materials.Screen);
    mat.toneMapped = false;
    return mat;
  }, [materials.Screen]);

  useLayoutEffect(() => {
    if (onLoadFn) {
      onLoadFn();
    }
  }, [onLoadFn]);

  useLayoutEffect(() => {
    setPhoneGroupRef(groupRef);
    setPhoneModelRef(modelRef);
    setPhoneScreenRef(screenRef);
  }, [setPhoneGroupRef, setPhoneModelRef, setPhoneScreenRef]);

  return (
    <group ref={groupRef} position={groupPos} rotation={groupRot} visible={visible}>
      <group ref={modelRef} dispose={null} scale={modelScale}>
        <group rotation={[Math.PI / 2, 0, 0]} scale={0.01}>
          <mesh geometry={nodes.M_Cameras.geometry} material={materials.cam} />
          <mesh geometry={nodes.M_Glass.geometry} material={materials['glass.001']} />
          <mesh geometry={nodes.M_Metal_Rough.geometry} material={materials.metal_rough} />
          <mesh geometry={nodes.M_Metal_Shiny.geometry} material={materials.metal_Shiny} />
          <mesh geometry={nodes.M_Plastic.geometry} material={materials.metal_rough} />
          <mesh geometry={nodes.M_Portal.geometry} material={materials['M_Base.001']} />
          <mesh ref={screenRef} geometry={nodes.M_Screen.geometry} material={screenMaterial} />
          <mesh geometry={nodes.M_Speakers.geometry} material={materials.metal_rough} />
          <mesh geometry={nodes.M_USB.geometry} material={materials.metal_rough} />
        </group>
      </group>
    </group>
  );
}

useGLTF.preload('/assets/models/Iphone15.glb');

The Amazon API for scraping is being blocked in my Axios

I need to create a form that sends a keyword to the server. Then, my server forwards this keyword to the Amazon server, which returns information such as name, price, photo, etc. After that, I need to send this information to the frontend.

The problem is that Amazon is blocking my axios. I tested with other API and the axios works.

my index.js that gets the keyword and sends to MY server:

const form = document.querySelector('form')
const keywordInput = document.querySelector('[data-key-word-input]')
const keywordResults = document.querySelector('[data-key-word-results]')

form.addEventListener('submit', async (e) => {
    e.preventDefault()

    let keyword = keywordInput.value.trim()

    console.log(keyword)

    if (!keyword) {
        alert('Enter a valid keyword')
        return
    }

    try {
        let response = await fetch(`http://localhost:3000/api/scrape?keyword=${encodeURIComponent(keyword)}`)
        let data = await response.json()

        keywordResults.innerHTML = ''

        if (data.length === 0) {
            keywordResults.innerHTML = 'Not found'
            return
        }

        data.forEach(product => {
            const productDiv = document.createElement('div')
            productDiv.classList.add('product')


            productDiv.innerHTML = `
        <h3>${product.title}</h3>
        <p>Rating: ${product.rating} (${product.reviews} reviews)</p>
        <img src="${product.imageUrl}" alt="${product.title}">
      `

            keywordResults.appendChild(productDiv)
        })
    }
    catch (error) {
        console.error('Error', error)
        alert('Failed to fetch data from server')
    }
})

my server, that sends the keyword to amazon and should send the response from amazon to my index.js:

const express = require('express')
const axios = require('axios')
const { JSDOM } = require('jsdom')
const cors = require('cors')

const app = express()

app.use(cors())

const PORT = process.env.PORT || 3000

app.get('/api/scrape', async (req, res) => {
    try {
        const keyword = req.query.keyword
        console.log('Palavra-chave:', keyword)

        const url = `http://www.amazon.com/s?k=${keyword}`

        const response = await axios.get(url)
        const html = response.data

        const dom = new JSDOM(html)
        const document = dom.window.document

        const products = []

        document.querySelectorAll('.s-result-item').forEach((item) => {
            const title = item.querySelector('h2').textContent.trim()
            const rating = parseFloat(item.querySelector('.a-icon-star-small').textContent.split(' ')[0])
            const reviews = parseInt(item.querySelector('.a-size-small').textContent.replace(/[^d]/g, ''))
            const imageUrl = item.querySelector('img').getAttribute('src')

            products.push({ title, rating, reviews, imageUrl })
        })

        res.json(products)

    } catch (error) {
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal Server Error', message: error.message });
    }
})

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`)
})

Why can’t I match the word I entered in the textbox to Firebase database?

// Form submission and user creation
document.getElementById(‘registrationForm’).addEventListener(‘submit’, function(event) {
event.preventDefault(); // Prevent the form from submitting

// Get user inputs
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var phone = document.getElementById('phone').value;
var enteredWord = document.getElementById('matched').value; // Get the entered word

// Reference to the Firebase Database
var database = firebase.database();

// Retrieve the stored word from Firebase
database.ref('messages/message').once('value', function(snapshot) {
    var storedWord = snapshot.val();

    // Check if storedWord exists and matches the entered word
    if (storedWord && enteredWord === storedWord) {
        // Validate password
        if (!validatePassword(password)) {
            alert('Password should be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one digit, and one special character.');
            return;
        }

        // Create user with email and password
        auth.createUserWithEmailAndPassword(email, password)
            .then(function(userCredential) {
                // User created successfully
                var user = userCredential.user;

                // Update user profile with phone number
                user.updateProfile({
                    displayName: firstName + " " + lastName,
                    phoneNumber: phone
                }).then(function() {
                    // Profile updated successfully
                    console.log("User profile updated with phone number.");
                }).catch(function(error) {
                    // Handle errors
                    console.error('Error updating user profile: ', error);
                });

                // Now you can add additional user data to your database
                database.ref('users/' + user.uid).set({
                    firstName: firstName,
                    lastName: lastName,
                    email: email,
                    phone: phone,
                    password: password
                })
                .then(function() {
                    // Clear input fields
                    clearFields();

                    alert('User registered successfully!');
                    // Redirect to index.html
                    window.location.href = "index.html";
                })
                .catch(function(error) {
                    console.error('Error adding user data: ', error);
                    alert('Error registering user!');
                });
            })
            .catch(function(error) {
                // Handle errors
                var errorCode = error.code;
                var errorMessage = error.message;
                console.error('Error creating user: ', errorMessage);
                alert(errorMessage);
            });
    } else {
        // Entered word does not match the stored word
        alert('The entered word does not match the stored word.');
    }
}, function(error) {
    console.error('Error retrieving data from Firebase: ', error);
    alert('Error retrieving data from Firebase. Please try again later.');
});

});

I want to retrieve the data that is stored in my database and match it to the textbox that I entered. If it matches, it will proceed to creating a user. I’m still learning JavaScript, and I can’t figure it out.

How to fix these buttons in HTML and CSS?

I was making a website and made different sections for it, a left-section with all the descriptions, and four big buttons in the middle to go to each category. I made another div tag in html .with class name “images-button”. I did the design I want and did the preview, I saw that it was under the previous button I did.

I expected it to work but it appeared under the other button, I tried to google what was going on, and it said to use the “display: flex;” in css. I tried that but it didnt do anything, I even tried doing “flex-direction: row;”, but that didnt do anything either.