Websocket Client not recieving message from server (Handshake OK, Server recieves messages)

My server establishes a connection with the JavaScript client, and upon opening, the server sends a message to the client. However, the client does not receive this message. The client successfully sends messages to the server after the connection opens, and the server receives these and all subsequent messages. Despite this, no messages sent by the server are received by the client.

This setup previously worked without issues on a DigitalOcean server. I have now migrated to my own server located at home, where I have configured port forwarding for managing POST requests and serving content through Nginx. However, I have been unable to determine why the WebSocket communication is not functioning as expected.

I consistently receive a message indicating “received 1001 (going away) then sent 1001 (going away),” which corresponds to an exception on close. This occurs when the page is left or refreshed. While the client correctly displays the opening and closing of the connection, it does not receive any messages from the server.

SERVER CODE:

async def handler(websocket, path) :
    current = None
    print("handling something")
    try :
        async for message in websocket :
            parsedClientMessage = json.loads(message)
            print(parsedClientMessage)
            if parsedClientMessage["type"] == "01" :
                parsedClientData = (parsedClientMessage['message'])
                current = parsedClientData['username'] if type(parsedClientData) is dict and parsedClientData['username'] in Read(storage) else id(websocket)
                if not current in clients :
                    clients[current] = {}
                clients[current][id(websocket)] = websocket
        await websocket.send(["connect", "Welcome to TerminalSaturn!", id(websocket)])

    except Exception as e :
        print(e)
    finally: 
        print(f"closed connection")
        if current in clients :
            if len(clients[current]) - 1 == 0 :
                del clients[current] 
            else :
                del clients[current][id(websocket)] 



async def main() : 
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ssl_context.load_cert_chain(certfile=cert_path, keyfile=key_path)
    async with websockets.serve(ws_handler=handler, host='0.0.0.0',port=1111, ssl=ssl_context):
        print("WebSocket server is running with SSL/TLS")
        await asyncio.Future() 

CLIENT CODE:

const wsUrl = 'wss://REDACTED:1111';
const socket = new WebSocket(wsUrl);
export var SID = null


socket.onopen = function (event) {
    console.log(event)
    socket.send(JSON.stringify({ type: '01', message: utils.getUserData() }));
};

socket.onmessage = function (event) {
    const data = JSON.parse(event.data)
    console.log("got msgs")
    console.log(event.data)
    const operations = {
        "rload": () => {
            utils.generateNotification("Admin", "Your data was updated and your page will be automatically refreshed in 3 seconds.")
            setTimeout(() => {
                location.reload()
            }, 1000 * 3);
        },
        "connect": () => {
            console.log("connected")
            utils.generateNotification("Server", data[1])
            SID = data[2]
        },
        "dcl": () => {
            if (utils.getUserData()) {
                utils.logOut()
            }
        }
    }
    if (data[0] in operations) {
        operations[data[0]]()
    }
    else {
        utils.generateNotification("Server", data)
    }
};

I have verified that my certificate is functioning correctly, as I am using WSS, and POST requests with CORS are working without any issues on this certificate. I have also confirmed that there are no antivirus programs, firewalls, or other security measures interfering with the connection. Despite extensive research and troubleshooting efforts, I have been unable to resolve this issue. The only error code I encounter is 1001.

Hygraph new content not showing up despite being queried

I am working on a personal portfolio website in NextJS and implementing a blog feature using hygraph for storing posts (built based off of the default nextjs blog). However I’m encountering a strange issue. I deleted and changed my posts and am left with a single post called ‘Test’. In my site the old 2 default example posts attached to the project (that I deleted) are showing up and not test.
portfolio blog screenshot However the default NextJS blog example they provided is working just fine. hygraph blog screenshot

My code is identical in terms of fetching data:
Hygraph starter project code to get all posts:

async function getPosts() {
  const client = HygraphClient()
  const allPosts = await client.request(AllPosts)
  return allPosts.posts
}
// later in the project
 const allPosts = await getPosts()

My project:

async function getPosts() {
    const client = HygraphClient()
    const allPosts = await client.request(AllPosts)
    return allPosts.posts
}
// later in the project
const allPosts = await getPosts()

I expected both to work the same.

I’m poorly versed in JS and am so close to finishing this project. Any and all would be greatly appreciated!

Fetching 2nd page of records and ignoring the first page

I’m trying out AirTable.js to access my records.

I am able to fetch my records from airtable if there are under 100, which is well-stated in their documentation. But if there are > 100 records the result is that the records after the first 100 survive, but the first 100 are lost.

The documentation explains that there is an adjustment to the code needed to capture 101+ records, but I can’t quite figure this one out.

const getRecords = () => {
    base(tableName)
      .select({
        view: 'Grid view',
        //sort: [{field: 'due_date', direction: "asc"}]
      })
      .eachPage(
        function page(fetchedRecords, fetchNextPage) {
          // This function (`page`) will get called for each page of records.
          setTickets([...tickets, ...fetchedRecords])
          fetchNextPage()
        },
        function done(err) {
          if (err) {
            console.error(err)
          }
        },
        // console.log('tasks: ',tasks)
      )
  }

  useEffect(() => {
    getRecords()
  }, [])

npm run build doesn’t include my src folder using vite

I am trying to build a vite website. I can successfully npm run dev and everything works but when I try to build it, only the index.html and the /public folder is used. My entire /src gets ignored. This is my current file organisation:

.
├── dist
├── index.html
├── node_modules
├── package-lock.json
├── package.json
├── public
│   ├── fonts
│   ├── gif
│   └── icons
├── readme.md
├── src
│   ├── html
│   ├── js
│   ├── scss
│   └── vite-env.d.ts

Content of my package.json

  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },

Is it how a vite project is meant to be organised ?
How can I build my project so that my src folder (with all my style, js and other pages) can be included ?
(and yes I have read Changing the input and output directory in Vite as well as other StackOverflow post as well as the vite config documentation and I am lost)

Why does overflow text not work in modal box?

So, I’m trying to do a modal by doing this:

<div className='transaction-modal'>
   <div className='transaction-forms'>
      Content of the box modal here
   </div>
</div>

And I did this CSS for it:

.transaction-modal {
    background-color: rgba(61, 61, 61, 0.48);
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 2;

    display: flex;
    justify-content: center;
    align-items: stretch;

    overflow-y: scroll;
}

.transaction-forms {
    background-color: white;
    border-radius: 20px;
    padding: 40px;
    max-width: 611px;
    justify-content: stretch;
}

But when I tried to use a Lorem500 in the bottom of my modal box HTML, it overflows the box and the .transaction-forms doesn’t create any white background.

Why does this happen? I think it has something to do about the display: flex inside the .transaction-modal, but I just can’t figure out a solution for that.

the form modal
text overflowing the box modal

I want the text to extend the modal box, which means it would create more white background and it doesn’t overflows the box.

TypeError: Cannot read properties of undefined (reading ‘dynamicSheet’)

I’m facing a TypeError: Cannot read properties of undefined (reading 'dynamicSheet') error while unit testing my scrollableComponent. I’m trying to mock the ref container’s scrollWidth and clientWidth to simulate different scrolling scenarios. However, the error persists even after mocking these properties.

Can you provide guidance on how to correctly mock the ref container and resolve this error? Are there any specific considerations or best practices I should follow when testing components with scrollable elements?

This is one of the test case:

const mockSetCurrent = jest.fn();
  const setMockRefElement = (node): void => {
    const mockRef = {
      current: node,
      // we need a setter here because it gets called when you
      setCurrent: mockSetCurrent(),
      // pass a ref to <component ref={ref} />
    };

    jest.spyOn(React, 'useRef').mockReturnValue(mockRef);
  };

  it('Expect only right scroll button to be visible', async () => {
    const currentScrollableContainer = {
      scrollWidth: 2500,
      clientWidth: 500,
      scrollLeft: 0,
    };

    // mock scrollableContainerRef
    setMockRefElement(currentScrollableContainer);

    const { getByLabelText } = render(Initial());

    const leftButton = getByLabelText('scroll left');
    const rightButton = getByLabelText('scroll right');

    expect(leftButton).not.toBeVisible();
    expect(rightButton).toBeVisible();

    click(rightButton);
    expect(mockSetCurrent).toHaveBeenCalled();

    // expect to scroll right the distance of clientWidth (by setting scrollLeft to its current value + clientWidth)
    expect(mockAnimate).toHaveBeenCalledWith(
      'scrollLeft',
      currentScrollableContainer,
      500,
    );
  });

Earlier when the component was a class based one this was the code and it was working perfectly:

  const setMockRefElement = (node): void => {
    const mockRef = {
      get current() {
        // jest dom elements have no width,
        // so mocking a browser situation
        return node;
      },
      // we need a setter here because it gets called when you
      // pass a ref to <component ref={ref} />
      set current(_value) {
        mockSetCurrent();
      },
    };

    jest.spyOn(React, 'createRef').mockReturnValue(mockRef);
  };

  it('Expect only right scroll button to be visible', async () => {
    const currentScrollableContainer = {
      scrollWidth: 2500,
      clientWidth: 500,
      scrollLeft: 0,
    };

    // mock scrollableContainerRef
    setMockRefElement(currentScrollableContainer);

    const { getByLabelText } = render(Initial());

    const leftButton = getByLabelText('scroll left');
    const rightButton = getByLabelText('scroll right');

    expect(leftButton).not.toBeVisible();
    expect(rightButton).toBeVisible();

    click(rightButton);
    expect(mockSetCurrent).toHaveBeenCalled();

    // expect to scroll right the distance of clientWidth (by setting scrollLeft to its current value + clientWidth)
    expect(mockAnimate).toHaveBeenCalledWith(
      'scrollLeft',
      currentScrollableContainer,
      500,
    );
  });

but when I changed the component to function it was showing rightButton as display: none hence it wasn’t visible.

Why I const “y” it give me a error :ReferenceError: Cannot access ‘y’ before initialization

I try to fix this but it say error many time and it give me a error :ReferenceError: Cannot access ‘y’ before initialization
I also change the const to var or let and change the position in the code but it not change
Plz who can fix me this code:

let x = toCelius(8,10);

function toCelius(c,f){

return (100+1) * (c+f);

}

document.getElementById(“demo”).innerHTML=x;

const y=to(9);

function to(){

return (y+10)

}

document.getElementById(“p1”).innerHTML=y;`

Getting the following error – Unhandled Runtime Error TypeError: (cartProducts || []).reduce is not a function

I tried to fix multiple times but it still returned the same error whenever I reload the page.

useEffect(() => {
  if (cartProducts) {
    const { total, qty } = (cartProducts || []).reduce(
      (acc, item) => {
        const itemTotal = item.price * item.quantity;

        acc.total += itemTotal;
        acc.qty += item.quantity;
        return acc;
      },
      { total: 0, qty: 0 }
    );
    setCartTotalAmount(total);
    setCartTotalQty(qty);
  }
}, [cartProducts]);

Can someone help me fix this problem?

Solutions for Chrome Out of Memory Issue

I’m developing a webpage that calls a large amount of data every minute and displays it using eCharts.js. However, after keeping the page open for 2-3 days, the browser throws an “out of memory” error on the client side.

Here are the potential solutions I’ve considered:

1.Setting the Cache-Control header on the server-side:

java

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");

2.Using setTimeout on the frontend to periodically reload the page:

javascript

setTimeout(function() {
    location.reload();
}, 60 * 60 * 1000); // Reload after 1 hour

3.Disabling Chrome hardware acceleration.

4.Periodically clearing the Chrome cache folder:

cmd

mklink /j "%LocalAppData%GoogleChromeUser DataDefaultCache" "R:TEMP"

Are any of these solutions appropriate for this problem? Or is there a better approach to handle this issue?

protecting out of memory

You are using Node.js 16.20.2. For Next.js, Node.js version >= v18.17.0 is required

i just install LTS verssion of node js 20.16.0 but in my system it not applicable properly like if i run command ” node -v ” it shows latest version but when i try to run my project its throw Error you aree using node js version 16 …….. many time i uninstall and install …..anyone have solution how an i do …….

so many time i try to uninstall nodejs and try to reinstall LTS version ofnode js but still not working .enter image description here

SVG in JS, script elements do not work in iPhone

I have written interactive HTML page using SVG in JS. This is my first time coding in JS and using SVG as well so please forgive me if I’m missing something basic. Below is source that shows this issue. It works correctly without issues in Chrome and Safari on my Macbook, works on Amazon tablet browser, works on Chorome in my Windows browser. DOES NOT work on my iPhone 13 Chrome or Safari. So this listing below is code from https://www.w3schools.com/graphics/svg_scripting.asp that shows the same issue where the dynamic changes in the script does not work. Any solutions is greatly appreciated.

<!DOCTYPE html>
<html>
<body>

<h2>SVG script Element</h2>

<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
  <circle id="circle1" cx="50" cy="50" r="25" style="fill:red;" />
  Sorry, your browser does not support inline SVG.
</svg>

<input type="button" value="Change Radius"  onclick="changeRadius()" />

<script>
function changeRadius() {
  document.getElementById("circle1").setAttribute("r", "50");
}
</script>

</body>
</html>

I can load HTML file into browsers on Mac, Windows, Amazon Tablet, the circle radius changes when you click on the button. This does not happen on Chrome or Safari on my iPhone 13 running iOS 17.6.1.

How to render HTML email content within a React App without crashing?

Here I’m trying to render an HTML email inside my React app. But getting an error pointed to the @ sign in the email.

Tried to sanitize with dompurify. But that is removing the whole email with <> part.
I don’t have control over the HTML content that is receiving.
Goal is to render the HTML content inside my app as it is.

This is an example code which is a part of the HTML I’am trying to render.

<div class='zd-comment' dir='auto'>
    '2024-08-01 14:17 - "John Doe" <[email protected]>
</div>

Here is what I have tried. converted the above into a JSON.

const htmlString = '<div class='zd-comment' dir='auto'>' +
    '2024-08-01 14:17 - "John Doe" <[email protected]>;' +
    '</div>';

Then sanitize using dompurify.

const sanitizedHTML = DOMPurify.sanitize(htmlString, null);

Then tried to render as both ways.

<div dangerouslySetInnerHTML={{ __html: sanitizedHTML }} />
/* with html-react-parser */
<div>{parse(sanitizedHTML)}</div>

how do I fix this?

Fetching Is done perfectly in localhost but not in deployed app | Vercel | NextJs | ReactJs | Javascript

Issue with Fetching Data in Deployed Vercel App but Works on Localhost

I’m facing an issue with fetching data in my React application. Here’s a simplified version of the code I’m using:

useEffect(() => {
  async function fetchData() {
    const res = await fetch("/api/flowers/getTopThreeData");
    const data = await res.json();

    setRosePetalGarlands(data.rosePetalGarlands);
    setJasmineGarlands(data.jasmineGarlands);
    setDecoration(data.decoration);
  }

  fetchData();
}, []);
  • Localhost: This code works perfectly fine on my local development server. The API endpoint /api/flowers/getTopThreeData returns the expected data, and everything functions as intended.

  • Deployed on Vercel: After deploying the app to Vercel, the same code doesn’t seem to fetch the data. I checked the Network tab in the browser’s DevTools, and it shows that the request is either failing or not fetching the expected data.

Request for Help

What could be causing this issue only in the deployed environment on Vercel? Is there something specific to Vercel’s deployment setup that I might be missing?


What I’ve Tried

  1. Checked Relative Path: I’m aware that using relative paths could cause issues, but other fetch requests in the same app using relative paths work fine even in the deployed environment.
  2. Cache Settings: I tried using no-cache to bypass any potential caching issues, but this didn’t solve the problem.

Additional Info

  • Environment: The issue is specifically with the deployed version on Vercel, while it works without any issues on localhost.
  • Other Fetches: Similar fetch requests are working fine on both localhost and the deployed server, which makes this issue puzzling.

environmental variables accessing in backend files

The following is the tree structure of the files file tree

This is code with error :
mailtrap.config.js

import { MailtrapClient } from "mailtrap";
import dotenv from "dotenv";
dotenv.config();

const TOKEN = process.env.TOKEN_MAILTRAP;
const ENDPOINT = process.env.ENDPOINT_MAILTRAP;
// making dynamic client and sender from the db(sender will be from the mailtrap and the user is from the user email from the DB)
export const mailtrapClient = new MailtrapClient({
  endpoint: ENDPOINT,
  token: TOKEN,
});
export const sender = {
  email: "[email protected]",
  name: "Mailtrap Test",
};

I am able to access the TOKEN_MAILTRAP , ENDPOINT_MAILTRAP from the .env file in the mailtrap directory but cannot access them from the root directory

complete backend directory
Here is the problem :
i can run the generateTokenAndSetCookie.js file with the root directory .env file

generateTokenAndSetCookie.js

import jwt from "jsonwebtoken";
const generateTokenAndSetCookie = (res,userId)=>{
    // token
    const token = jwt.sign({userId},process.env.JWT_SECRET,{
        expiresIn:"7d"
    });
    // setting cookie in the response
    res.cookie("token",token,{
        httpOnly:true,
        secure:process.env.NODE_ENV === "production",
        sameSite:"strict",
        maxAge:7*24*60*60*1000,
    });
    return token;
}
export default generateTokenAndSetCookie;

Is there any errors in the code of mailtrap.config.js

In generateTokenAndSetCookie.js the file can access the environmental variables of root directory but in mailtrap.config.js it cannot access the environmental varibales of root directory but can access the environmental variables of mailtrap directory

it came undefined when i console log the environment variables from the root directory

How to ensure user logout with Web Worker when the computer goes to sleep

I’m using a Web Worker to set a setTimeout that automatically logs out the user after 10 minutes of inactivity. However, I’ve encountered an issue where if the user’s computer goes to sleep, all processes, including the Web Worker, stop running. This means that even if the session should have expired, the user remains logged in when the computer wakes up.

Is there a way to ensure that the user is logged out even if the computer goes to sleep and wakes up later? How can I handle this situation effectively?

Any suggestions or solutions would be greatly appreciated!