Express.js – Custom Header “Auth” not being read properly in if statements for incoming requests

I am making a server connected pygame script that handles multiplayer movements and updates it on the player’s screen. For every request in the python file I add an extra header named “Auth” that I use in the get/put/post functions for express, in order to differentiate programs and authenticate http requests. My issue here is that when I send over a JSON file, the response on the python program which GETs the file is simply response code 200, which I cannot decode from JSON

For example:

Defining data:

let data = require(__dirname + "\gamedata.json")

If statement:

app.get('/', (req, res) => {
    Auth = presentRequest(req)
    //Other code before this
    } else if (Auth == '2DDR') {
        res.json(data)
        console.log("Sent")
    }
})

Python request:

reqjson = request() // Class that makes requests, params: method, headers, data to send
response = reqjson.makereq('GET', {'Auth': '2DDR'}, None)
print(response.json())
datadict = response.json()
players = datadict.get('Players', [])

Throws:


Traceback (most recent call last):
File “ControlAndDisplay.py”, line 145, in
print(response.json())
File “AppDataLocalProgramsPythonPython310libsite-packagesrequestsmodels.py”, line 900, in json
return complexjson.loads(self.text, **kwargs)
File “AppDataLocalProgramsPythonPython310libjson_init_.py”, line 346, in loads
return _default_decoder.decode(s)
File “AppDataLocalProgramsPythonPython310libjsondecoder.py”, line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File “AppDataLocalProgramsPythonPython310libjsondecoder.py”, line 355, in raw_decode
raise JSONDecodeError(“Expecting value”, s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I’ve tried putting the exact path, changing the name of the json, messing around with the Auth, but nothing works and I don’t know what to do. It was supposed to send back over the JSON to the client for further handling but instead as mentioned it just sends over the response code 200 as “<Response [200]>”

Hostinger VPS for Minecraft Modded Server error “Killed by user”

I recently bought a VPS on Hostinger for a minecraft server, I have my own modpack and I don’t think I have any errors related to additional mods (despite some lines asking for additional mods that I installed but the error hasn’t changed).

My server is in forge 47.1.0 (mc 1.20.1) and all my mods are normally in the correct version.

I used FileZilla to put the mods in the server folders

Server storage space is 44 GB

When I launch the server it stops after a few seconds with the error “Killed by user” even though I’ve done nothing.

If you need the console log i can send you that.

Someone would be kind enough to help me, I’ve spent over 9h trying to figure it out without it working, so I’m referring to you, please save me!

I’d like to know how to fix this error and be able to launch the server with my mods and my current version so that I can play with my friends.

save and exit to edit-mode

i have tables with edit button on the side. if i click the edit button it works fine, i can change/modify and the button edit change to save button just in case you need to save update the changes in the table. when i click the save button it updates the table but the editable cells in row table, does not exit, even i hit the save button it didn’t exit the edit mode. i used javascript for my coding. can you help me please

i just add this line because in my other code work it works.

function saveCV(rowId) {
    var row = document.querySelector("tr[data-id='" + rowId + "']");
    var editableCells = row.querySelectorAll(".editable");

    var formData = new FormData();

    editableCells.forEach(function (cell) {
    var fieldName = cell.getAttribute("data-field");
    var newValue;

    if (fieldName === "cvdate") {
        var inputElement = cell.querySelector("input");
        newValue = inputElement ? inputElement.value : "";
    } else if (fieldName === "branch") {
        var selectElement = cell.querySelector("select");
        newValue = selectElement ? selectElement.value : "";
    } else if (fieldName === "booknumber" || fieldName === "costcenter") {
        var selectElement = cell.querySelector("select");
        newValue = selectElement ? selectElement.value : "";
    } else {
        var inputElement = cell.querySelector("input");
        newValue = inputElement ? inputElement.value : "";
    }

    formData.append(fieldName, newValue);
    });

    var actionsCell = row.querySelector(".center-align-column");
    actionsCell.innerHTML = `
    <button class='edit-button' onclick='editCV(${rowId})'>Edit</button>
    <button class='delete-button' onclick='deleteCV(${rowId})'>Delete</button>`;

    row.removeAttribute("data-edit-mode"); // Clear the edit mode flag
    row.removeAttribute("data-original-values"); // Clear the original values data attribute
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "updateCV.php?id=" + rowId, true);
    row.setAttribute("data-edit-mode", "true"); // Restore edit mode
    row.classList.add("editing"); // Add 'editing' class to indicate edit mode
    xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
           // exitEditMode(row);
        } else {
           // Update failed
          alert("Failed to update record");
        }
    }
    };
    xhr.send(formData);

}

above code, im expecting it to save/update changes in my table and exit from edit mode

usePathname() returning null AND useRouter() causing “Error: NextRouter not mounted” and “Error: invariant expected app router to be mounted” errors

I’m using NextJS version 13.4.4, and I’ve been trying to implement active navlinks. The issue is that for this solution, I want to access the current URL, but every attempt to do so ends up failing. My folder structure is like this:

  • .next
  • components
    • Header
      • header.tsx
      • navbar.tsx <<<< the file i’m working in
  • pages
    //my pages are here

my navbar code looks like this:

'use client'

import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useRouter } from 'next/router';

export const Navbar = (props:any):JSX.Element =>{
    const links = [
        {
            path: "/",
            name: "Home"
        },
        {
            path: "/about", 
            name: "Resume"
        },
        {
            path: "/projects",
            name: "Projects"
        },
        {
            path: "/contact",
            name: "Contact Me"
        }
    ];

    const router = useRouter();
    const url = usePathname();
    //const url = router.pathname;

    return(
        <nav className="navbar navbar-dark navbar-expand-lg border-bottom topNav">
            <div className="container-fluid">
                <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"></span>
                </button>
                <div className="collapse navbar-collapse justify-content-center w-100 mt-3 mt-lg-auto" id="navbarNav">
                    <ul className="navbar-nav justify-content-center">
                        {links.map((link, index):JSX.Element =>{
                            return(
                            <li className="nav-item px-5" key={index}>
                                <Link className={
                                    url === link.path ? "nav-link text-white navLink activeLink"
                                    : "nav-link text-white navLink"
                                    } aria-current="page" href={link.path}>{link.name}</Link>
                            </li>
                            )
                        })}
                    </ul>
                </div>
            </div>
        </nav>
    );
}

All suggestions welcome.

I’ve tried

import { useRouter } from 'next/router

export default Navbar = () =>{
   const router = useRouter();
   const url = router.pathname;
   ...
}

which results in my app crashing and the ‘NextRouter not mounted’ error.

I’ve tried

import { usePathname } from 'next/navigation'

export default Navbar = () =>{
   const url = usePathname();
   ...
}

which results in ‘url’ being null.

And I’ve also tried this just to see what options I have for getting the URL from this

import { useRouter } from 'next/navigation

export default Navbar = () =>{
   const router = useRouter();
   console.log(router)
   ...
}

which resulted in “Error: invariant expected app router to be mounted”

Cant get dispatch to properly run my then catch afterwards

Error

  const dispatch = useDispatch();
  const sessionUser = useSelector((state) => state.session.user);
  const group = useSelector((state) => state.session.group);
  const history = useHistory();
  const [name, setName] = useState("");
  const [about, setAbout] = useState("");
  const [type, setType] = useState("");
  const [isPrivate, setIsPrivate] = useState("");
  const [city, setCity] = useState("");


  const [state, setState] = useState("");
  const [errors, setErrors] = useState({});

const handleSubmit = async (e) => {
    e.preventDefault();
    if (sessionUser) {
      setErrors({});
      return dispatch(
        sessionActions.createGroup({
          organizerId: sessionUser.id,
          name,
          about,
          type,
          isPrivate,
          city,
          state,
        })
      )
        .then((res) => {
          if (res.ok) {
            history.push(`/groups/${group.id}`);
          }
        })
        .catch(async (res) => {
          const data = await res.json();
          if (data && data.errors) {
            setErrors(data.errors);
          }
        });
    }
  };

i get that error when creating a group on first submit but my createGroup function still dispatches. the page doesnt reroute, however when submitting a new group form without closing the tab or refreshing my reroute works and I dont get the error.

ive tried everyhting i can think of but my knowledge of dispatch is still beginner level

How do I add all the font-faces available for a specific Google Font?(in JS)

I’m looking for a simple way to generate all the possible google fonts URL for a specific Google font, I want to have all the available styles(bold/italic/normal) and weights available.(I’m working on a image editor and I’d like to load every font from a font-family when a user wants to use a font)

I’m using this fontsource API Route to get data on the fonts available.

Does anyone have a good simple solution for this?

I wrote this function of awful spaghetti code, it seems to kinda work for most fonts but for some fonts the link is invalid(and I’m not even sure it’s loading all possible variations):

    function generateGoogleFontURL(font) {
    const BASE_url = `https://fonts.googleapis.com/css2?family=`
    if (font.weights.length == 0) {
      return [`${BASE_URL}${font.family}`]
    }
    if (!font.variable) {
        if (font.styles.includes("italic")) {
          return font.weights.map(x => `${BASE_URL}${font.family}:ital,wght@0,${x};1,${x}`)
        }
        return [`${BASE_URL}${font.family}:wght@${font.weights.join(';')}`]
    }
    if (font.weights.length > 1) {
      const minWeight = font.weights[0]
      const maxWeight = font.weights[font.weights.length - 1]
      if (font.styles.includes("italic")) {
          return [`${BASE_URL}${font.family}:ital,wght@0,${minWeight}..${maxWeight};1,${minWeight}..${maxWeight}`]
      }
      else {
        return [`${BASE_URL}${font.family}:wght@${minWeight}..${maxWeight}`]
      }
    }    
    if (font.styles.includes("italic")) {
        return [`${BASE_URL}${font.family}:ital,wght@0,${font.weights[0]};1,${font.weights[0]}`]
    }
    return [`${BASE_URL}${font.family}:wght@${font.weights[0]};${font.weights[0]}`]
  }

Validate dynamic txt file with unicode tags using javascript?

I need to validate a text file with a dynamic content, but it’s generated with unicode tags for each line. I use other file as a baseline to compare the files and check if the file created is equal to the expected.

i split both files with n and compare each line from the files, but i have some issues with encondig/unicode characters.

Tried using this regex https://regex101.com/r/nXTkrP/1, but it fails when comparing both files, as unicode seems to change when i copy the content from expected to baseline to be compared.

Basic logic would be:

var txtFile = readFileText(file).split("n");
var baselines = readFileText(baseline).split("n");

if (file.indexOf(baseline) = -1){
    var equals = true;
}

Is there any way to “force” encondig of both files to compare, or any other suggestion on using regex to ensure the layout is the same and the content is the same?

Why can’t I reset my array with setState?

In my camera component, I want to upload the photos to a storage bucket every 3 photos. I use state in react to save my image blobs to an array. Everything works perfectly for the first 3 photos but afterward, I am not able to reset my array to be empty again and a seemingly random number of photos is uploaded to my bucket.

  let [blobs, setBlobs] = useState([]);

  const capturePhoto = async () => {
    const photo = await camera.current.takePhoto();
    fetch(photo.path)
      .then(res => {
        setBlobs([...blobs, res._bodyBlob]);
        console.log('blobs', blobs.length, blobs);
      })
      .catch(err => {
        console.log('err', err);
      });
    checkLength();
  };

  const checkLength = async () => {
    if (blobs.length >= 2) {
      // upload files to a folder with the current date in a firebase cloud bucket
      const datestring = new Date().toLocaleString('de-DE');
      blobs.forEach((blob, i) => {
        uploadFile(blob, datestring + '/' + (i + 1) + '.jpg');
      });
      // reset state
      setBlobs([]);
      sendNotification('Photos uploaded');
      toggleDialog();
    }
  };

I console logged my array and the size only increases. Also, it starts console logging with zero although I already added an element likely because setState() is asynchronous.
I tried to await the reset by wrapping it in a promise, but that sadly did not work either.
How can I upload the blobs to the cloud once there are 3 of them and reset the list afterward?

weird behavior using useRef array

so i am essentially trying to render a list of jsx components.
now i will be removing from and adding to this list.
i have useRef([]) set up so i can access these components, but it doesnt work as expected.

here is the code.

import React,{useRef,useState,useEffect} from 'react';

export function App(props) {
  let headrefs=useRef([]);
  let [idx,setIdx]=useState(3);
  let number=useRef(0);
  
  let arr=useRef([<div className='App'>
      <div ref={(ele) => (headrefs.current[idx -1 + number.current] = ele)} className="hello1">div1</div>
      <div ref={(el) => (headrefs.current[idx + number.current] = el)} className="hello2">div2</div>
      <div>div to be removed</div>
      <button className="clicker">tap me</button>
      <div>just some div</div>
      
  </div>]);
  
  console.log(arr.current);

  useEffect(()=>{

  let lbutton=document.querySelector('.clicker');
  

  let card=headrefs.current[idx + number.current];
  console.log('outside mainf',card);

  

  let mainf=()=>{

    console.log( 'inside mainf',card);

    const copyier={...arr.current[0]};
    arr.current.unshift(copyier);
    arr.current.pop();
    const copyier2={...arr.current[0].props};
    arr.current[0].props=copyier2;
    const copyier3=[...arr.current[0].props.children];
    arr.current[0].props.children=copyier3;

    let size=arr.current[0].props.children.length;

    arr.current[0].props.children.unshift(
       (
        <div ref={(elem) => (headrefs.current[idx -2 + number.current] = elem)} className="hello3">small div3</div>
       )
    )

    

     for (let i = 3; i < size; i++) {
      let swap = arr.current[0].props.children[i + 1];
      arr.current[0].props.children[i + 1] = arr.current[0].props.children[i];
      arr.current[0].props.children[i] = swap;
     }

                    

    arr.current[0].props.children.pop();


    number.current=number.current+1;
    setIdx(idx-1);
  }

  lbutton.addEventListener('click',mainf);

  return ()=>{
    lbutton.removeEventListener('click',mainf);
  }
  },[idx])

  return (
    <>
      {arr.current}
    </>
  );
}

i do realise that i require a unique key while rendering, and i will fix that soon.

but the issue, is that, after the click of the button,

the line console.log( ‘inside mainf’,card);
prints the div with hello1 instead of hello2

which is the expected div.
it prints correctly in the console.log(‘outside mainf’,card);

how do i fix this?

tell me if any clarification is needed.
thank you.

how to reassign javascript event listeners

i’m building a web app which allows you to drop HTML elements onto an area.

these elements are built using JS classes with their own properties/methods to customise them.
a user can build a template by selecting elements from the pane and when a new object instance is created they come with a number of event listeners, upto here i understand how to implement it and have done so, but i’m unfamiliar with the concept of how to retain the event listeners after the user saves their template.

for example

lets say i newly created a template, whilst still in the session the browser has all the event listeners but once the template is saved and a new session is created, how do i then get back the event listeners?

**in summary: my goal is to understand how to implement a way to reassign lost event listeners to the elements within the users template without having to re-build them.
**
here is my code:

this calls the new paragraph object

const para = document.querySelector('.paragraph');
const head = document.querySelector('.header');

para.addEventListener('click', () => {
    
    new Paragraph(container);

});

this is the paragraph class

class Paragraph{
    constructor(target){
        this.name
        this.id
        this.arrayObjects = []
        this.updateDOM(target);
        this.addEvents();
    }

    updateDOM(target){
        let numOfParas = target.childElementCount || 0;
        this.id = `paragraph${(numOfParas + 1)}`
        let content = `<p id="${this.id}">Text</p>`;
        target.innerHTML += content;
    }

    addEvents(){

        window.addEventListener('click', (e) => {
            if(e.target.id == this.id){
                console.log(document.querySelector(this.id))
                this.updateProperties();
                this.setAllEvents();
            }
        });
    }

    setName(value){
        document.querySelector('#'+this.id).innerText = value
        this.name = value;
    };

    updateProperties(){
        let propertiesPane = document.querySelector('.container-properties');
        propertiesPane.innerHTML = '';
        this.arrayObjects.push(this.UIInput());

        this.arrayObjects.forEach((item) => {
            propertiesPane.innerHTML += item
        });
    };

    setAllEvents(){
        this.setEventInput()
    }

    UIInput(){
        return `<input type="text" id="${'input-'+this.id}">`;
    }

    setEventInput(){
        document.querySelector('#input-'+this.id).addEventListener('keyup', (e) =>{
            //console.log(e)
            this.setName(e.target.value);
        });
    }

}

i’m not sure yet how to implement the concept and unable to find any online resource.

i just need the concept of implementation.

Error 404 undefined on a deployed page on Vercel using NextJS

I created a next JS app, Upon deployment, I tried going to subpages, I had a few, for example /reservations, upon reaching that route, I get a error message saying error 404 page not found, I tried replicating it in terminal using the npm run build function, I got the following error
Error message.

This is the file structure
File structure

I suppose it is a middleware error, so adding middleware.ts code for refrence

export { default } from "next-auth/middleware"

export const config={
    matcher:[
        "/trips",
        "/favorites",
        "/reservations",
        "/pets"

    ]
}

Although, While using the website in a dev enviorment, the website and the pages work just fine, so there is no error with API calling, What could possibly be wrong?

FireFox or Safari + JavaScript Parses an Input Field Type Number Incorrectly

If you have a form field type of number and use that value in JavaScript, the results are not always consistent (with FireFox and Safari so far.)

A value of 10.0 in the input field will parse correctly as the floating number 10.0. However, if you have a “naked” decimal (e.g. 10.) it will parse as NaN.

While this question is similar, it does not address the contextual help I would like to use with reportValidity() and this.checkValidity(). My intended eventual use is to leverage .on('input change', function (e) {//do processing here});.

I have included a Fiddle of an MRE as an example:

https://jsfiddle.net/lbussy/rv0swbox/

In FF and safari:

  • 1 parses as 1
  • 1. parses as NaN
  • 1.0 parses as 1

ELI5 what is happening in this function please

    function pigIt(str){
        return str.replace(/(w)(w*)(s|$)/g, "$2$1ay$3")
    }

I understand what this outputs and the basics of the replace, but if someone could go through and explain step by step whats actually happening within the replace brackets, I would really appreciate it.

I understand that it’s regex but not sure what the steps are here

Is there a way to configure an animation loop in PixiJS with ticker.maxFPS that is as controllable as a manual requestAnimationFrame process or GS?

I have 3 code examples using PixiJs line animation rendering. The animation loop can be controlled manually with requestAnimationFrame and works well but doesn’t have other aspects of the Pixi.TICKER class such as controlling FPS or delta methods (perhaps this last part is not accurate).

My question is 2 fold.

  1. Why does the Pixi.TICKER ticker.add() not work as well as the manual requestAnimationFrame() or the Green Sock gsap functionality. why when it is set to maxFPS = 1 it doesn’t slow the rate efficiently?
  2. Is there a preferred method 1 vs the other when using pixi for 2d rendering?
    Here is a related codepen

Effectively it is not using the ticker loop via ticker.add Code here:

let maxFPS = 5; // Set the desired maximum frame rate
let frameDuration = 1000 / maxFPS; // Calculate the duration of each frame in milliseconds

let lastFrameTime = 0;

function animate(timestamp) {
  let elapsed = timestamp - lastFrameTime;

  if (elapsed >= frameDuration) {
    // Render the frame
    renderer.render(stage);
    var y = Math.random() * h;
    draw(dx, y, PIXI.LINE_CAP.ROUND);

    lastFrameTime = timestamp;
  }

  requestAnimationFrame(animate);
}

// Start the animation loop
requestAnimationFrame(animate);

Again, the control here for the event loop FPS is good. But do I still get the benefit of the ticker functions?

Here is an abstraction using ticker.add() which allows for direct control of the FPS via less code abstraction: Note, this abstraction doesn’t provide good control with ticker.maxFPS = xx At setting 1 it seemingly still very fast.

let ticker = PIXI.Ticker.shared;
ticker.autoStart = false;
ticker.maxFPS = 1; // does not work very well 1 is not really 1 FPS it's more like 5
ticker.minFPS = 0; // Set the desired minimum frame rate

ticker.add(function (time) {
    graphen.clear();
    graphen2.clear();
    graphen3.clear();
    var y = Math.random() * (h);
    // console.log('Dx ', dx);
    // console.log('Y ', y);
    draw(dx, y, PIXI.LINE_CAP.ROUND);
    renderer.ticker.update();
    renderer2.ticker.update();
    renderer3.ticker.update();
})

// Start the animation loop
ticker.start();

Lastly for good measure, I tested Green Sock and it performs more like the manual method and seems to work well and is accurate to the manual requestAnimationFrame method. Code example:

gsap.ticker.fps(5);
gsap.ticker.add(() => {
    // renderer.ticker.maxFPS = 10
    graphen.clear();
    graphen2.clear();
    graphen3.clear();
    var y = Math.random() * (h);
    // console.log('DX ', dx);
    // console.log('Y ', y);
    draw(dx, y, PIXI.LINE_CAP.ROUND);
    renderer.ticker.update();
    renderer2.ticker.update();
    renderer3.ticker.update();
})