app.use(express.json()) is not working in express version [email protected] , but works fine in [email protected]

import express from "express";
const app = express();
import dotenv from "dotenv";
import path from "path";
let _dirname = path.resolve();
import cors from "cors"
import { router } from "./routes.js";
import connectDB from "./src/helper/dbConnection.js";
dotenv.config();
const PORT = process.env.PORT;

app.use(cors)
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(_dirname, "public")));
router(app);

connectDB();

app.listen(PORT, () => {
  console.log("Server listening on PORT:", PORT);
});

**
I am getting error like
TypeError: Cannot destructure property ‘name’ of ‘req.body’ as it is undefined.

I tried a fix for it
instead of writing it like

  const { name } = req.body;

I replaced it with this

  const { name } = req.body ||{};

it resolves the issue but i need the solution from the app.use(express.json()) itself

What is the replacement for app.use(express.json()) in the latest version ? Do they have any ?

how to make a floating copy text that slowly disspear for my website

so my current website https://asmophacy.github.io/website/
does this ()
then it go and copy it to clipboard this is my current js code for my email

function copyText() {
    /* Copy text into clipboard */
    navigator.clipboard.writeText("[email protected]").then(() => {
        // Optional: Add feedback here if you want
        console.log("Email copied via copyText function!");
        // alert("Email copied!"); // Simple feedback
    }).catch(err => {
        console.error("Failed to copy email via copyText function:", err);
    });
}

document.addEventListener('DOMContentLoaded', () => {
// email copy code
    const emailLink = document.querySelector('a.social-button.proton');

    if (emailLink) {


        emailLink.addEventListener('click', (event) => {
            event.preventDefault(); // Prevent navigating to the link's href
            copyText(); // Call your function here

            // Optional: Add the visual feedback logic here if needed,
            // using iconSpan and originalIconHTML like before,
            // since copyText() itself doesn't handle it.
            const iconSpan = emailLink.querySelector('span.icon');
            if (iconSpan) {
                const originalIconHTML = iconSpan.innerHTML;
                iconSpan.textContent = 'Copied';
                 setTimeout(() => {
                    iconSpan.innerHTML = originalIconHTML;
                 }, 2000);
            }
        if (svg) {
            const originalIconHTML = iconSpan.innerHTML;
            iconSpan.textContent = 'Copied';
             setTimeout(() => {
                iconSpan.innerHTML = originalIconHTML;
             }, 2000);
        }
            
            
            
    });

    } else {
        console.warn('Could not find the email link element (a.social-button.proton).');

i want it to instead be like steam where it float and slowly dissapear how do i do that? like it keep the original details there and just have a floating copied text goes up and dissapear
thanks!
(my first post)

In JavaScript how can I get the text insertion point where dragged text was dropped into a texteara?

When text is selected and then dragged into a textarea the browser moves the caret around in the textarea as you drag, showing where the dragged text will be dropped, and when the text is dropped it goes into place at that spot. This is all good default behavior, but now I want to modify the dropped text, but only if it’s dropped into an empty line. In this case I want the dropped text to be surrounded with extra newlines so it ends up on its own paragraph. If the text is dropped into the middle of an existing paragraph I don’t want to change the dropped text.

My problem is how to know where the text is dropped. During either the ‘drop’ event or the ‘dragover’ event I can’t figure out what property to access or what function to call to get the caret position. My workaround at this point is to require the user to first click in the target textarea at the position where the dragged text should be dropped, then I call event.preventDefault() during dragover so that the caret isn’t visible at all during dragover so it’s clear the insertion point can’t be changed, then during ‘drop’ I check event.target.selectionStart to know where the text was dropped.

This basically works, but it’s unnatural for the user to have to click in the desired spot ahead of time. A standard textarea lets the insertion point change during dragover, and I want my special textarea to work that way, too.

Why is my React component not re-rendering after updating state?

I’m building a React app, and I have a component that fetches data and sets it in the state. However, when the state updates, the component doesn’t seem to re-render. I expected the updated data to be shown automatically after the state change, but it’s not happening.

I tried using useState to manage the data and calling the state setter function inside an API fetch. I expected that updating the state would cause the component to re-render with the new data, but the component remains the same. I also tried forcing an update manually, but it didn’t seem to help.

Jitter problem with differential line growth

I’m trying to create a smooth animation using differential line growth.
I can have a snake on the screen grow and fill the space which I want.

It’s made up out of a number of nodes with two forces working on them (cohesion and separation)

It grows and moves as expected but it never settles down, once it fills the space certain particles (usually ones in a straight line) will jitter and jump up and down at a high speed.

I’m sure this is a common problem but I can’t figure out how to fix it.
I would like the snake to settle once it’s fully filled the space but need to fix the jittering first.

here is all the relevant code which will recreate the problem if you press play.
https://editor.p5js.org/spaciousmind/sketches/wNp-8jyop

How to display each part of a comma-separated string on a new line (or table) in HTML using JavaScript?

I’m trying to split a comma-separated string in JavaScript and display each part on a new line within an HTML page. I have the following code:

<head>
    <script>
        const testString = "Hello,World";
    </script>
</head>
<body>
    <div id="output"></div>

    <script>
        const parts = testString.split(',');
        document.getElementById('output').innerHTML = `
            <p>${parts[0]}</p>
            <p>${parts[1]}</p>
        `;
    </script>
</body>

It works in some HTML editors but not others.

I want to make it more dynamic, so it can handle any number of comma-separated values. How can I modify this code to iterate over the split parts and display each one on a new line or all values in a new row in a table, regardless of how many parts there are?

It should work in HTMLFiddle.

how to grind farcaster

how to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcasterhow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefae

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcasterhow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefae

to someoen tell medvsaf
affdsfafaasfefae
to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcasterhow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefae

to someoen tell medvsaf
affdsfafaasfefae
to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcasterhow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefae

to someoen tell medvsaf
affdsfafaasfefae
to someoen tell medvsaf
to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcasterhow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefaehow to grind farcaster

to someoen tell medvsaf
affdsfafaasfefae

to someoen tell medvsaf
affdsfafaasfefaewdfrwsefs
affdsfafaasfefae

How to programmatically zoom in on a webpage and improve resolution (like Ctrl + does)?

In some webpages where there is a <canvas> element, when i tried every single methode of mking the browser bigger, the page bigger… I did found some methodes that will make everything big, but the I check the canvas element it’s like it still the same resolution just got bigger, and in some cases it even stay in the same size. But when I try manual Keyboard shortcut Ctrl +, the page zooms in adn the canvas element get a good resolution even if its bigger (i don’t know why, maybe it got reloaded in the backend).
I also tried the built-in Keyboard actions in Playwright Python, but seems to do nothing I don’t know why.
So after that I used PyAutoGui to simullate the user clicking Ctrl +, but the disadvantage of this solution is the PyAutoGui will zoom in in whatever page your on, no matter if its chrome or no, so you need to stay on chrome when executing the scrapping code.
Is there a reliable way to programmatically trigger the same effect as Ctrl + —specifically one that improves the resolution of elements—using automation tools like Playwright, or perhaps through browser APIs?

Parallax Image Responsive Resize

I have a parallax page that works (well enough for now) on computer monitors: the images heights are 100vh and the width is 100%. When I look at the same page on a phone the parallax itself is working, but the images heights are no longer 100vh, instead they are quite small. The 100vh height is priority, so I don’t mind if the sides of the images get cut off, but I can’t seem to figure out how to do it.
Here’s what I have been working with:

<div class="hppblock">
  <img src="/Collection.jpg" data-speed="2" class="img-parallax">
  <h1>Collection</h1>
</div>
<div class="hppblock">
  <img src="/Single.jpg" data-speed="1.5" class="img-parallax">
  <h1>Bespoke Gallery</h1>
</div>
<div class="hppblock">
  <img src="/Detail.jpg" data-speed="1" class="img-parallax">
   <h1>Detail</h1>
</div>

With this JS (though I don’t this is affecting the issue one way or the other)

$('.img-parallax').each(function(){
  var img = $(this);
  var imgParent = $(this).parent();
  function parallaxImg () {
    var speed = img.data('speed');
    var imgY = imgParent.offset().top;
    var winY = $(this).scrollTop();
    var winH = $(this).height();
    var parentH = imgParent.innerHeight();
    var winBottom = winY + winH;

    if (winBottom > imgY && winY < imgY + parentH) {
          var imgBottom = ((winBottom - imgY) * speed);
          var imgTop = winH + parentH;
          var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
    }
    img.css({
      top: imgPercent + '%',
      transform: 'translate(-50%, -' + imgPercent + '%)'
    });
  }
  $(document).on({
    scroll: function () {
      parallaxImg();
    }, ready: function () {
      parallaxImg();
    }
  });
});

And the CSS:

.hppblock{
  width: 100%; /*I've also tried width: auto*/
  height: 100dvh;
  position: relative;
  overflow: hidden;
}
.hppblock h1{
  position: relative;
  display: block;
  text-align: center;
  color: #D0BFAD;
  font-size:7.5vw;
  margin: 0;
  top: 50%;
  transform: translateY(-50%);
}
.img-parallax {
  width: 100vmax;
  z-index: -1;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%,0);
  pointer-events: none
}

I tried messing around with these settings, too, but things got wonky fast:

background-position: center;
background-repeat: no-repeat;
-webkit-background-size: 100%; 
-moz-background-size: 100%; 
-o-background-size: 100%; 
background-size: 100%; 
-webkit-background-size: cover; 
-moz-background-size: cover; 
-o-background-size: cover; 
background-size: cover;

And this also wonkified everything:

@media screen and (max-width: 800px) {
    .hppblock{
        object-fit: cover;
        display: flex;
        background-position: center;
        background-repeat: no-repeat;
        justify-content: center;
        align-items: center;
        text-align: center;
        min-height: 100vh;
}

Any help would be greatly appreciated, as I feel like I’m going around in circles.
As seen on a phone screen.

How to use dagre (or similar graph library) to construct only the edges given fixed node positions?

I need to draw a graph whose nodes’ positions and sizes are predetermined (from an external source) and cannot be changed. It is straightforward to draw the nodes using a library like d3. The difficulty arises in drawing the edges. I understand that libraries like dagre have functionality to figure out the layout of nodes and edges and make the graph look presentable. But for me, the challenge is in using dagre to work with fixed node positions and make it compute only the edge paths.

Here is a small working example of use dagre + d3 to draw a simple graph represented by an adjacency list.

// Simple adj list for my graph
const adjList = {
    "A": ["B", "C"],
    "B": ["D"],
    "C": [],
    "D": []
};

// Fixed positions.
// This will be from an external source which CANNOT be changed.
// I can't figure out to pass this to dagre's layout engine.
const fixedPositions = {
  A: { x: 300, y: 50 },
  B: { x: 150, y: 150 },
  C: { x: 450, y: 150 },
  D: { x: 100, y: 250 }
};

const g = new dagre.graphlib.Graph();
g.setGraph({});
g.setDefaultEdgeLabel(function() { return {}; });

// Adidng nodes and edges to  graph
Object.keys(adjList).forEach(node => {
    g.setNode(node, { label: node, width: 50, height: 30 });
});

Object.entries(adjList).forEach(([node, edges]) => {
    edges.forEach(target => {
        g.setEdge(node, target);
    });
});

// Run the layout algorithm (this part computes the layout considering everything and can't be forced to work with my fixed positions)
dagre.layout(g);

// Create the SVG
const svg = d3.select("#graph")
    .append("svg")
    .attr("width", "100%")
    .attr("height", "100%");

const inner = svg.append("g");

// zoom behavior
const zoom = d3.zoom().on("zoom", function(event) {
    inner.attr("transform", event.transform);
});
svg.call(zoom);

// Create nodes
const nodes = inner.selectAll(".node")
    .data(g.nodes())
    .enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function(v) {
        const node = g.node(v);
        return `translate(${node.x}, ${node.y})`;
    });

// draw rectangles for nodes
nodes.append("rect")
    .attr("width", function(v) { return g.node(v).width; })
    .attr("height", function(v) { return g.node(v).height; })
    .attr("x", function(v) { return -g.node(v).width / 2; })
    .attr("y", function(v) { return -g.node(v).height / 2; });

// print labels for nodes
nodes.append("text")
    .attr("text-anchor", "middle")
    .attr("dominant-baseline", "central")
    .text(function(v) { return v; });

// Create edges (this will use dagre's layout below)
const line = d3.line()
    .x(d => d.x)
    .y(d => d.y)
    .curve(d3.curveBasis);

const edges = inner.selectAll(".edge")
    .data(g.edges())
    .enter()
    .append("path")
    .attr("class", "edge")
    .attr("d", function(e) {
        const edge = g.edge(e);
        return line(edge.points);
    });


const graphBounds = inner.node().getBBox();
const width = svg.node().clientWidth;
const height = svg.node().clientHeight;
const scale = Math.min(width / graphBounds.width, height / graphBounds.height) * 0.9;
const translate = [
    (width - graphBounds.width * scale) / 2 - graphBounds.x * scale,
    (height - graphBounds.height * scale) / 2 - graphBounds.y * scale
];

svg.call(zoom.transform, d3.zoomIdentity
    .translate(translate[0], translate[1])
    .scale(scale));
#graph {
    width: 100%;
    height: 600px;
    background-color: #f9f9f9;
}
.node rect {
    stroke: #333;
    fill: #fff;
    stroke-width: 1px;
}
.node text {
    font: 12px sans-serif;
}
.edge {
    stroke: #333;
    stroke-width: 1px;
    fill: none;
}
<!DOCTYPE html>
<html>
<head>
    <title>Simple Graph</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="https://unpkg.com/@dagrejs/[email protected]/dist/dagre.js"></script>
</head>
<body>
    <div id="graph"></div>
</body>
</html>

My only problem with this is that there doesn’t seem to be a way to pass my fixedPositions to force it to use them for placing nodes, and then do the layout for just the edges.

    const fixedPositions = {
      A: { x: 300, y: 50 },
      B: { x: 150, y: 150 },
      C: { x: 450, y: 150 },
      D: { x: 100, y: 250 }
    };

    // cannot do
    // dagre.layout(g, fixedPositions);

Is there a way to achieve this either with dagre or some other library? This question asks about this in a theoretical perspective but I’m asking in a more practical sense with the use of available open source libraries or otherwise.

The last resort is to just draw the edges manually using straight lines but then the graph does not look presentable. For example, this might be a result if I manually draw straight line edges for a different (not the only in my code) graph.

enter image description here

Should I use node.js, or PHP for a leaderboard? [closed]

I’m trying to make a leaderboard for a game. I am using JavaScript(and html) for the game itself. I feel like it would be easier to use JS for the server-side, but I use MySQL for databases. So should I use PHP instead? Can node.js connect to MySQL? And, because I am using object-oriented programming for the game itself, should I transmit the data with object-oriented programming?
Edit: I removed some stuff to make the question more focused.

Chrome/Safari blocking JavaScript (user originated) blob URL downloads (sandbox blocking download)

I’m running a simple web application that creates a JSON out of some data the user manipulates in a web UI. The page is served as a GitHub Pages hosted site. What I’m trying to do is to create a download link on that page which I pass through JavaScript’s Blob API’s to create a download URL that is programmatically clicked. The action, as shown below, is initiated by a user initiated click.

While doing this, I am intermittently seeing Chrome (Version 135.0.7049.115 (Official Build) (arm64)) and certain versions of Safari indicate ‘sandbox’ errors when clicking the button. I am not able to reproduce this on the Safari on my machine, but I do know that some folks had issues (ironically, some folks had older versions of Safari so it seems that newer versions are fine).

Error (Chrome):

Download is disallowed. The frame initiating or instantiating the download is sandboxed, but the flag ‘allow-downloads’ is not set. See https://www.chromestatus.com/feature/5706745674465280 for more details.*emphasized text*

As I understand this error, it is detecting that the download is being blocked because Chrome maybe does not think this is user initiated? Not quite sure what I could do to make this work since the event is very much user-triggered?

Application (note: @click directive is being used since I’m using Vue.js – Vue3 specifically):

<script>
    function downloadBtn() {
        const data = generateRandomData();
        const jsonStr = JSON.stringify(data, null, 2);
        const blob = new Blob([jsonStr], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'data.json';

        document.body.appendChild(a);
        a.click();

        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
</script>
<template>
    <button @click="downloadBtn">PRESS ME</button>
</template>

Should I use setImmediate for caching responses in Redis after sending HTTP response?

I’m working on a Node.js + Express app where I use Redis to cache API responses. Here’s a simplified version of my route:

router.get("/get-acadamies", async (req, res) => {
  try {
    const redkey = "acadamy:all";
    const cached = await redisGet(redkey);

    if (cached !== null) {
      return res.json({
        success: true,
        message: "Result fetched from Redis cache",
        data: cached,
      });
    }

    const result = await academiesModel.find({}).limit(1000);

    // Cache result in background
    setImmediate(async () => {
      await redisSet(redkey, result, 3600);
    });

    return res.json({
      success: true,
      message: "Result data fetched from DB successfully",
      data: result,
    });
  } catch (error) {
    return res.json({
      success: false,
      message: "Something went wrong",
      data: [],
    });
  }
});

HTML/CSS Marquee with dragging NO JQUERY

Looking for a pure HTML/CSS solution to replace the deprecated tag.
Must not be in JQuery and have minimal JS (if any at all.)
One last condition: I should be able to move the marquee by dragging it (a scroll bar at the bottom is fine too)

Why are flex items expanding vertically in my wrapped flex container?

I have the following CSS setup using Flexbox:

.container {
  width: 350px;
  height: 500px;
  border: 2px solid black;
  display: flex;
  flex-wrap: wrap;
  align-content: stretch;
  align-items: stretch;
}

.container div {
  width: 80px;
  font-size: 2rem;
  text-align: center;
  background-color: lightblue;
}
  <body>
<div class="container">
  <div class="box" style="background-color: #ff5722">1</div>
  <div class="box" style="background-color: #ff9800">2</div>
  <div class="box" style="background-color: #ffc107">3</div>
  <div class="box" style="background-color: #ffeb3b">4</div>
  <div class="box" style="background-color: #cddc39">5</div>
  <div class="box" style="background-color: #8bc34a">6</div>
</div>
  </body>

When I add multiple items to the container, they wrap into multiple rows as expected. However, each item is stretching vertically, and I want to understand why that happens.

Is the following understanding correct?

When we have wrapping enabled via flex-wrap: wrap, then by default align-content: stretch will kick in. This causes the flex lines (rows) to grow taller to fill the container’s cross-axis (vertical) space. Then align-items: stretch makes the individual items within each line expand to fill the height of their line.

Any clarifications or visual explanations would be really helpful.

Reference

I’ve already read this helpful explanation on the difference between align-content and align-items:
What’s the difference between align-content and align-items?