Server error in different browsers when i use my local server [closed]

I am writing and testing a full-stack application. My frontend is uploaded to hosting and has the address – https://planner.cifra-plus.com.ua. And my server is on a local computer with a database. For the test, I run the server through the ngrok tunnel, I registered, and received a free static domain – https://grateful-heroic-mite.ngrok-free.app.
In requests, I use axios, I have public requests – $public, and authorized with a token – $auth. Public requests work without problems, but for requests with authorization I get a CORS error. This error is in both desktop Google Chrome and mobile Google Chrome, in Microsoft Edge, and also in Safari on the iPhone.


I am sending screenshots

  1. axios request settings
  2. CORS settings on the server
  3. as well as responses in the Google Chrome browser to an authorized request, as well as the response from the Microsoft Edge browser.
    Links:
    https://ibb.co/4n6S2LsN
    https://ibb.co/NdkrwBj0
    https://ibb.co/7dV8sb8v
    https://ibb.co/Tqgvb44k

Using wildcards in JavaScript [duplicate]

I’m writing a program which generates random letters and determines if there exists a word containing those letters in the order they’re generated.

No matter which letters are generated, the program always returns “Invalid permutation”. So for example, it doesn’t recognise that the letters i, t, and a are a valid permutation, as these can make up the word “dictionary”.

My code is below. What am I doing wrong?

//define dicitionary and alphabet
const dictionaryArray = ["alligator", "breadcrumb", "creation", "dictionary", "elephant", "farm", "general"];
const alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

/*implement function to generate a random number. 
In conjunction with alphabet array, this will generate 
random letters */
function Random(maxNumber) {
    return Math.floor(Math.random() * maxNumber);
  }

//generate random letters
var genLet1 = alphabet[Random(26)];
var genLet2 = alphabet[Random(26)];
var genLet3 = alphabet[Random(26)];

//concatenate with wildcards
var wildGen = "*" + genLet1 + "*" + genLet2 + "*" + genLet3 + "*";

function checkPermutationValidity(string) {

  if (britishDictionary.includes(string)) {
    console.log("Valid permutation");
  } else {
  console.log("Invalid permutation");
    }
}
checkPermutationValidity(wildGen);

Why does my error handler only work for the first error, but fails on subsequent requests?

I’m trying to handle errors globally in Node/Express PostgreSQL/pg with an error handler function, and when I send a Postman request to the API for creating users to try to create a user with an email that already exists in the database, it first gives a proper custom response – as the duplicateError function is called due to the error having the 23505 code – and it creates a new custom operational error and sends it as the response. But if I then try to do it again, a TypeError happens instead of the previous PG error (duplicate key value violates unique constraint) so the response sent is instead the generic response for non operational errors

TypeError: Class constructor CustomError cannot be invoked without 'new'
    at C:Users\Desktopproject1backendnode_modulespg-poolindex.js:45:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async createUserService (file:///C:/Users//Desktop/project1/backend/src/models/userModel.js:15:18)
    at async createUser (file:///C:/Users//Desktop/project1/backend/src/controllers/userController.js:21:19) {
  status: 'fail',
  statusCode: 500
}

This is the db query function:

export const createUserService = async (name, email) => {
  const result = await pool.query(
    'INSERT INTO users(name,email) VALUES ($1, $2) RETURNING *',
    [name, email],
  );
  return result.rows[0];
};

This is the global error handling:

const prodErrors = (res, error) => {
  if (error.isOperational) {
    res.status(error.statusCode).json({
      status: error.status,
      message: error.message,
    });
  } else {
    res.status(500).json({
      status: 'error',
      message: 'Something went wrong, try again later',
    });
  }
};

const duplicateError = (error) => {
  const msg = 'Email must be unique';
  return new CustomError(msg, 400);
};

export const errorHandler = (error, req, res, next) => {
  error.status = error.status || 'fail';
  error.statusCode = error.statusCode || 500;
  console.log(error);

  if (process.env.NODE_ENV === 'development') {
    devErrors(res, error);
  } else if (process.env.NODE_ENV === 'production') {
    if (error.code == 23505) {
      error = duplicateError(error);
    }
    prodErrors(res, error);
  }
};

The custom error class:

class CustomError extends Error {
    constructor(message, statusCode) {
        super(message)
        this.statusCode = statusCode;
        this.status = statusCode>=400 && statusCode < 500 ? 'fail' : 'error';

        this.isOperational = true;

        Error.captureStackTrace = (this, this.constructor)
    }

}
export default CustomError;

For other errors, for example invalid email, it works fine. But for the duplicate value error it only works on the first request, after which it gives the TypeError. I’ve been looking for an answer the whole day and have no idea why it’s not working. I’m using the latest version of Express

Also, if I try doing it directly in the db query function, the same thing happens. First error is caught and a new custom error is thrown, but the second error does not contain the code and is only a TypeError

export const createUserService = async (name, email) => {
  try {
    const result = await pool.query(
      'INSERT INTO users(name,email) VALUES ($1, $2) RETURNING *',
      [name, email],
    );
    return result.rows[0];
  } catch (error) {
    // Handle PostgreSQL unique constraint error (23505)
    if (error.code === '23505') {
      throw new CustomError('Email must be unique', 400); // Use 400 for a Bad Request error
    }
    // If it's some other error, throw it again to be handled by a global error handler
    throw error;
  }
};

One more thing, if I instead of sending the error to the middleware, just console.log the error in the try catch block above, it’s the same pg error on all requests. So the issue happens after the first error is sent somehow

Why does threshold on IntersectionObserver not work on my element?

IntersectionObserver does not work as intended on my element in React. As you can see in code I have threshold set to 0.5 but animations are fired as soon as they appear on the screen and I do not understand why. Can someone explain? (I’ve included CSS just in case that has something to do with it because I’m not sure.)

Demo video

import { buttonHoverAnimation, rotateAnimation } from "../../animations/animations";
import backgroundImage from "../../assets/images/pexels.jpg";
import smileIcon from "../../assets/icons/smile.svg";
import "./ExploreCard.css";
import { useEffect, useRef } from "react";
import { slideAnimation } from "../../animations/animations";
type ExploreCardProps = {
  reverse?: boolean;
};

function ExploreCard({ reverse }: ExploreCardProps) {

  const buttonHover = buttonHoverAnimation({}, {}, 30);
  const contentRef = useRef<HTMLDivElement>(null);
  const imageRef = useRef<HTMLDivElement>(null)
  // Handler Slide animation
  useEffect(() => {
    if (!contentRef.current) return;
    const animation = slideAnimation(
      contentRef.current,
      reverse ?
      [-1000, 0] : [1000, 0]
    );
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        animation.play();
        observer.unobserve(entries[0].target);
      }
    }, { threshold: 0.5 });
    observer.observe(contentRef.current);
    return () => {
      observer.disconnect();
    };
  });
  // Handle rotate animation ,
  useEffect(() => {
    if (!imageRef.current) return;
    const animation = rotateAnimation(imageRef.current)
    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) {
        animation.play();
        observer.unobserve(entries[0].target);
      }
    },
     { threshold: 0.5 }
    );
    observer.observe(imageRef.current);
    return () => {
      observer.disconnect();
    };
  }, []);


  return (
    <div className={`explore-card ${reverse ? "reverse" : ""}`}>
      <div className="explore-image-wrapper" ref={imageRef}>
        <img src={backgroundImage} alt="Background-image" />
      </div>
      <div className={`explore-card-popup ${reverse ? "reverse" : ""}`}>
        <h2>2X</h2>
        <p>Faster</p>
      </div>
      <div className={`explore-content-wrapper ${reverse ? "reverse" : ""}`}ref={contentRef}>
        <div className="explore-content-icon">
          <img src={smileIcon} alt=":)" />
          <p>QUICK</p>
        </div>
        <div className="explore-content-header">
          <h1 className="explore-content-header-bold">HOME</h1>
          <h1 className="explore-content-header-italic">Refresh</h1>
        </div>
        <div className="explore-content-description">
          Experience the ultimate expert support — Creating spaces where comfort
          and productivity thrive.
        </div>
        <div className="explore-content-button">
          <button
            onMouseOver={buttonHover.handleMouseIn}
            onMouseOut={buttonHover.handleMouseOut}
          >
            <span>EXPLORE</span>
            <span>EXPLORE</span>
          </button>
        </div>
      </div>
    </div>
  );
}

export default ExploreCard;
@font-face {
  font-family: intern-light;
  src: url('../../assets/fonts/static/Inter_18pt-Thin.ttf');
}

@font-face {
  font-family: intern-regular;
  src: url('../../assets/fonts/static/Inter_18pt-Light.ttf');
}

@font-face {
  font-family: intern-bold;
  src: url('../../assets/fonts/static/Inter_24pt-Black.ttf');
}

@font-face {
  font-family: intern-italic;
  src: url('../../assets/fonts/static/Inter_18pt-ThinItalic.ttf');
}

.explore-card {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  position: relative;
  gap: 2vw;
  margin-top: 15vh;
  overflow: hidden;
  height: 50vh;
}

.explore-content-wrapper {
  width: 35%;
  display: flex;
  padding: 7%;
  display: inline-block;
}

.explore-content-icon > p{
  font-family: intern-regular;
  margin-left: 10px;
  font-weight: 500;
  letter-spacing: 2px;
}

.explore-content-icon {
  display: flex;
}

.explore-content-icon > img {
  width: 30px;
}

.explore-image-wrapper {
  display: flex;
  height: 50vh;
  width: 25%;
  border-radius: 70px;
  overflow: hidden;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2;
}

.explore-image-wrapper > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.explore-card-popup {
  top: 10%;
  left: 30%;
  border-radius: 50px;
  position: absolute;
  height: 34%;
  width: 13%;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10px);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  -webkit-box-shadow: 0px 10px 50px -10px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 0px 10px 50px -10px rgba(0, 0, 0, 0.75);
  box-shadow: 0px 10px 50px -10px rgba(0, 0, 0, 0.75);
  z-index: 3;
}

.explore-card-popup > h2 {
  font-family: intern-regular;
  font-weight: 100;
  font-size: 30px;
  margin: 0;
}

.explore-card-popup > p {
  font-family: intern-light;
  font-size: 20px;
  font-weight: 600;
  margin-top: 0;
  letter-spacing: 2px;
}

.explore-content-header {
  display: flex;
  font-size: 60px;
}

.explore-content-header > h1 {
  margin-top: 5px;
  margin-right: 10%;
  margin-bottom: 5px;
}

.explore-content-header-bold {
  font-family: intern-regular;
  font-weight: 300;
}

.explore-content-header-italic {
  font-family: intern-italic;
  font-weight: 100;
}

.explore-content-description {
  font-family: intern-regular;
  font-size: 18px;
  letter-spacing: 2px;
  line-height: 30px;
  margin-bottom: 30px;
}

.explore-content-button > button {
  font-family: intern-regular;
  height: 1.3rem;
  font-size: 1.3rem;
  background: none;
  border: 0;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.explore-content-button > button > span {
  position: relative;
  transition: transform 0.7s, opacity 0.7s;
  margin: 0;
}

.explore-card.reverse {
  flex-direction: row-reverse;
}
.explore-card-popup.reverse {
  left: 57%;
}

Jest Manual Mocking Not Functioning as Expected

I’m trying to mock mssql. I can see by debugging that the mock sql.connect function is being called but it doesn’t seem to be returning after being called and it’s causing the unit test to throw a timeout error and the test fails.

Here is the code that I’m testing:

            sql.connect(config.dbConnection, (err) => {
            if (err) {
                logger.info(err);
            } else {
                sql.query(`select * from XXX';`, (err, result) => {
                    if (err) {
                        logger.info("Error executing call: ", err);
                    } else {
                        resolve({ status: httpStatusCodes.StatusCodes.OK, apiResponse: result.recordsets[0][0].ZipCode });
                    }
                });
            }
        });

Here is the unit test:

it("should call sql.connect", async function () {
    const response = await regionalization.regionalizationAPI("02878");
    expect(response.status).toEqual(200);
});

Here is the manual mock file:

function connect() {
return jest.fn().mockReturnValue();

}

I have a breakpoint set in the connect function and the debugger stops in the function. No matter what mock function I use the execution isn’t returned back to the code and I keep seeing a timeout error.

Deactivate Cross Site Origin Protection [duplicate]

There are already several questions on this topic, but none have really been answered yet.
I really want to disable cross site origin security to access an iframe element and control it via javascript.

I realize that this is a security feature, but then you have to be able to disable it, especially if you explicitly want it in a certain context.
I know it’s possible because you can select the iframe via the hover cursor in the dev tools of any browser and then all javascript commands work directly in the iframe.
However, if I try this without using the cursor select function (directly with Javascript), I keep getting the error:

Command:

var iframe = document.querySelector('iframe');
iframe.contentWindow.contentDocument;

Error:
Uncaught SecurityError: Failed to read a named property 'contentDocument' from 'Window': Blocked a frame with origin “https://example.com” from accessing a cross-origin frame

How could I get around this?
Are there any browsers that allow me to bypass these functions?

Transfer Session between Javascript and PHP

Is there possible to convert Seesion data from Javascript to PHP and vice versa? Something like (I’m not sure about the input format in javascript.):

<script>
     session.setAttribute("username","John");
</script>

<?php
     echo $_SESSION["username"]; // it will write "John"
?>

How can I unit test Graphql Upload in api using Vitest

I wrote a test which creates a Venue with attachments property which is of Graphql Upload type. But when I try to run the test, it fails with error "message": "Variable "$attachments" got invalid value { fieldName: "1", filename: "valid-image.png", mimetype: "image/png", encoding: "7bit" } at "attachments[0]"; Upload value invalid.” basically Upload value invalid.

In backend the attachments is structure like that

{
  fieldName: '1',
  filename: 'Screenshot 2023-09-05 193500.png',
  mimetype: 'image/png',
  encoding: '7bit',
  createReadStream: [Function: createReadStream]
}

Unit test

it("should create a venue with valid attachments", async () => {
    const imagePath = join(__dirname, "test-files", "valid-image.png");
    const variables = {
      organizationId: orgId,
      name: `Test Venue ${faker.string.alphanumeric(5)}`,
      description: "Test venue with valid attachments",
      capacity: 50,
      attachments: [
        {
          fieldName: "1",
          filename: "valid-image.png",
          mimetype: "image/png",
          encoding: "7bit",
          createReadStream: () => createReadStream(imagePath),
        },
      ],
    };

    const result = await mercuriusClient.mutate(Mutation_createVenue, {
      headers: { authorization: `bearer ${authToken}` },
      variables,
    });

    console.log('result is ', result);
   
  })

I have never tested FileUpload so I’m not sure whether I’m correctly testing it or not.

Any help would be appreciated.

When exactly does navigator.clipboard.readText() prompt for user permission in Chrome?

Consider the following HTML file:

<div contenteditable="true" id="editable"></div>

<script>
  const editable = document.getElementById('editable');
  editable.addEventListener('paste', () => {
    navigator.clipboard.readText().then(x => console.log(x));
  });
</script>

Consider the following two scenarios in Chrome browser only:

  1. I press Ctrl+V (or Cmd+V on macOS) to paste text into the textbox. In this case, I do not get any permission prompt, and the console.log works.
    Note that this appears to be contradictory to the MDN documentation which states:

    Reading requires the Permissions API clipboard-read permission be granted. Transient activation is not required.

  2. If I run document.execCommand('paste', false) from the content script of a Chrome extension which has both the "clipboardRead" and the "clipboardWrite" permissions, then I do get the permission prompt. It is not clear to me why execCommand has a different behavior compared to the scenario above. The prompt is shown in this image:

    permissions prompt

My question: could anyone explain the behavior in line with relevant documentation, spec or Chromium source code?

text shape feature using Fabric.js

want to add support for curved text or text that follows a defined shape/path. The goal is to allow users to input text and dynamically adjust it to follow a curve (e.g., circular text, text along a wave) while maintaining standard text features like font size, color.

Datadog post custom metrics from Browser

I am struggling to send data to custom metrics from Browser API. Docs are clear on how to do it from Node.js, but in Browser context it looks like there is no other option but to send it via HTTP request.

Did anyone find a browser’s api method to do that, or did datadog just skip this feature for browsers?

The datatog in my web app is configured the CDN way:

    <script type="text/javascript" src="https://www.datadoghq-browser-agent.com/datadog-logs-us.js"></script>
    <script>
      DD_LOGS.init({
        // config
      });
    </script>

“How to extract real-time product ranking from an e-commerce site instead of DOM order?” [closed]

I am trying to extract the real ranking of products from an e-commerce site, but my script currently assigns ranks based on DOM position, which does not match the actual ranking shown on the site.

For example, my code incorrectly displays Rank #7 as Rank #4 because it is reading products in the order they appear in the HTML structure, rather than their real-time ranking on the site.

What I Have Tried:
✅ Checking HTML Attributes: I inspected product elements in DevTools but couldn’t find data-rank, bestseller-badge, or other useful attributes.
✅ Extracting Rank from Visible Text: Some products have ranking labels, but not all of them.
✅ Looking at Network Requests (XHR/Fetch API): I noticed that the ranking might be fetched dynamically from an API, but I am unsure how to extract this data.

document.querySelectorAll(".product-card").forEach((product) => {
let rankElement = product.querySelector(".bestseller-badge");
let realRank = rankElement ? rankElement.innerText : "Unknown";
console.log(`Real Rank: ${realRank}`);

});

What I Need Help With:
❓ How does an e-commerce site typically store and update product rankings?
❓ How can I retrieve the real ranking (e.g., sorted by best sellers) instead of relying on DOM order?
❓ Should I look at JavaScript-rendered elements or API responses for this data?
❓ How can I fetch ranking data dynamically if the site loads it asynchronously?

I am a computer science student but still learning JavaScript and web scraping techniques. Any guidance would be greatly appreciated!