Consistent “Incomplete response received from application” – NodeJS app on cPanel with Express

I’m working on a NodeJS API. For the sake of clarification, we’ll say my API url is api.mydomain.com. The endpoint that I’m having trouble with is /ts/password. This endpoint’s function is to send a GET request to my Teamspeak3 server webquery to generate a temporary password (using the npm package axios). Everything seems to work as intended when I’m running the API locally on my machine in VS Code, but when I upload it to my hosting provider via cPanel’s built-in NodeJS app module, this /ts/password endpoint returns “Incomplete response received from application”
when a request is sent to it. I have reviewed my code countless times, and can’t seem to find any reason as to why this is happening; but it’s even more confusing how it works on my local machine when the endpoint is called via localhost, but not when called through my domain when hosted on cPanel. I’ve also tried reinstalling node modules, but wasn’t successful there either.

const configFile = require("./config.json")

const express = require("express")
const mysql = require("mysql")
const app = express()
const bodyParser = require("body-parser")
const axios = require("axios")
const panelHeaders = {
    headers: { Authorization: `Bearer ${configFile.panelApiKey}` }
}
const dbConn = mysql.createConnection({
    host: configFile.mdbHost,
    user: configFile.mdbUsername,
    password: configFile.mdbPassword,
    database: configFile.mdbName
})

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function generateTsPassword(length) {
    let result = '';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
}

app.get("/ts/password", (req, res) => {
    const endpoint = "/ts/password"
    if(req.headers.authorization === configFile.apiKey) {
        const tempPw = generateTsPassword(8)
        const url = "http://ts3.operationsrp.com:10080/1/servertemppasswordadd?api-key=" + configFile.ts3ApiKey + "&pw=" + tempPw + "&duration=300&desc=Via+OperationsRP+API"
        axios.get(url)
            .then(function (response) {
                if(response.data.status.code === 0) {
                    res.status(200).send({status: "SUCCESS", statusCode: 200, password: tempPw})
                } else if(response.data.status.code === 1539) {
                    res.status(400).send({status: "BAD_REQUEST", statusCode: 400, message: "An error occurred with the downstream request: required parameter not found. Try again later or contact development."}) // occurrs when a required url query param sent via the teamspeak api url is missing
                }
            })
            .catch(function (error) {
                if(error.response.data.status.code === 7) {
                    res.status(500).send({status: "ERROR", statusCode: 500, message: "An unknown error occurred with the downstream request, and it was cancelled. Try again later or contact development."}) // usually occurrs when the virtual server id is incorrect/not found
                } else if(error.response.data.status.code === 1538) {
                    res.status(404).send({status: "NOT_FOUND", statusCode: 404, message: "An error occurred with the downstream request: invalid command or endpoint. Try again later or contact development."}) // occurrs when the command/endpoint sent via the teamspeak api url is not valid
                } else if(error.response.data.status.code === 5122) {
                    res.status(401).send({status: "UNAUTHORIZED", statusCode: 401, message: "An error occurred with the downstream request: invalid API key. Try again later or contact development."}) // occurrs when the api key sent via the teamspeak api in the url query param is not valid
                } else if(error.response.data.status.code === 5124) {
                    res.status(401).send({status: "UNAUTHORIZED", statusCode: 401, message: "An error occurred with the downstream request: missing API key. Try again later or contact development."}) // occurrs when no api key is supplied in the request to the teamspeak api
                } else {
                    res.status(500).send({status: "ERROR", statusCode: 500, message: "An unknown error occurred with the downstream request. Try again later or contact development."}) // could really be anything
                }
            })
    } else {
        res.status(401).send({status: "UNAUTHORIZED", statusCode: 401, message: "Missing or invalid API key."})
    }
})

Firebase is saying that the ID doesn’t match

I’ve made a website for my school, but I’m trying to expand on it. It’s not that secure with auth and such, so I’m making a server for users to login, then when they want to update their settings on the website, it will send a request to the server to do so.

I’m currently trying to work on the user logging in. When I go to the “/login” route, it brings me to the Google login page. I login and it brings me to the “/app” route. In the console, I get the log below.

FirebaseAuthError: Firebase ID token has incorrect "aud" (audience) claim. Expected "school-progress-g" but got "1090170234957-5ntr48jf178o9befpp5n0603hoh7m2rh.apps.googleusercontent.com". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
    at FirebaseTokenVerifier.verifyContent (/rbd/pnpm-volume/124c6272-9622-4f1d-925a-072a4f9e9ad7/node_modules/firebase-admin/lib/auth/token-verifier.js:239:19)
    at /rbd/pnpm-volume/124c6272-9622-4f1d-925a-072a4f9e9ad7/node_modules/firebase-admin/lib/auth/token-verifier.js:160:18 {
  errorInfo: {
    code: 'auth/argument-error',
    message: 'Firebase ID token has incorrect "aud" (audience) claim. Expected "school-progress-g" but got "1090170234957-5ntr48jf178o9befpp5n0603hoh7m2rh.apps.googleusercontent.com". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.'
  },
  codePrefix: 'auth'
}

I would also appreciate some help with how I would be able to continue developing this login system into my website, after the error is solved. Here are my code files:

server.js

const cookieParser = require("cookie-parser");
const express = require("express");
const admin = require("firebase-admin");

const serviceAccount = require("./serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://school-progress-g-default-rtdb.firebaseio.com",
});

const PORT = process.env.PORT || 3000;
const app = express();

app.engine("html", require("ejs").renderFile);
app.use(express.static("static"));

app.use(cookieParser());

const firebaseAuthMiddleware = (req, res, next) => {
  const idToken = req.cookies.idToken || "";
  
  if (idToken == "") {
    return next();
  }

  admin
    .auth()
    .verifyIdToken(idToken)
    .then((decodedToken) => {
      req.user = decodedToken;
      next();
    })
    .catch((error) => {
      console.log(error);
      next();
    });
};
app.use(firebaseAuthMiddleware);

const { google } = require("googleapis");

const oauth2Client = new google.auth.OAuth2(
  "1090170234957-5ntr48jf178o9befpp5n0603hoh7m2rh.apps.googleusercontent.com",
  "XXXXXXXX (censored)",
  "https://scpr-server-version.glitch.me/callback"
);

app.get("/login", (req, res) => {
  const authUrl = oauth2Client.generateAuthUrl({
    access_type: "offline",
    scope: ["https://www.googleapis.com/auth/userinfo.email"],
  });
  res.redirect(authUrl);
});

app.get("/callback", async (req, res) => {
  const { tokens } = await oauth2Client.getToken(req.query.code);
  res.cookie("idToken", tokens.id_token);
  res.render("app.html");
  return false;
  res.redirect("/app");
});

app.get("/logout", (req, res) => {
  res.clearCookie("idToken");
  res.redirect("/login");
});

app.get("/app", (req, res) => {
  if (req.user) {
    res.render("app.html");
  } else {
    res.redirect("/login");
  }
});

app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

I appreciate any help I can get! <3

I’ve tried changing the client ID in server.js with my Firebase ID, but it just causes more errors.

Can an aborted HTTP fetch from a web browser (abortController abort()) be recognized in a Go backend app (using the Context package)?

I’m having problems troubleshooting why a cancelled request in the frontend isn’t reaching a backend API. In other words, sending a GET/POST request using axios works just fine. But once .abort() kicks in, the network console shows request cancelled, which is also fine, but the backend does not recognized this cancellation.

The frontend code is identical to the following:
https://github.com/axios/axios/issues/4338#issuecomment-1002364900

Unfortunately, according to the backend api logs, the requests goes through as normal. No canceled request or error appears in the backend logs.

On a related note, when a similar request is made from other clients, like using curl in a terminal, or from a desktop app: Postman, the backend picks up the cancellation and the logs show: error: timeout: context canceled

Is it just not possible for javascript’s abort() to be picked up in the backend (Go app using ctx.Done()? Is there something special a CURL request is signaling that an aborted request from the browser isn’t?

Typescript passing whole object vs single key when only single key is needed by React FC

I am contemplating whether I should pass the whole object, vs passing the single required key of the object to my React Functional Component.
I know Typescript passes by reference so there is not any performance impact, but I want to know what is a better practice as far as programming paradigms and best practices are concerned.

The object in question is fairly big, having 11 keys. A couple of keys have objects and array of objects as values.

What I need in my FC is just a key of type string.

How to implement a Nested list with multi-selection

Currently there is the following list implementation:

<select id='optSelect' multiple>
                            
                                <optgroup label='Option1'>
                                    <option value='Option1' style='font-size: 15px;'>Option1</option>
                                    <option value='Option12' style='font-size: 15px;'>Option12</option>
                                    <option value='Option13' style='font-size: 15px;'>Option13</option>
                                </optgroup>
                            
                                <optgroup label='Option2'>
                                    <option value='Option21' style='font-size: 15px;'>Option21</option>
                                    <option value='Option22' style='font-size: 15px;'>Option22</option>
                                    <option value='Option23' style='font-size: 15px;'>Option23</option>
                                </optgroup>
                            
                                <optgroup label='Option3'>
                                    <option value='Option31' style='font-size: 15px;'>Option31</option>
                                    <option value='Option32' style='font-size: 15px;'>Option32</option>
                                    <option value='Option33' style='font-size: 15px;'>Option33</option>
                                </optgroup>
                           
                        </select>
                

It is necessary to implement it so that when hovering over, for example, the Option2 element on the right at the Option2 level, a list of elements with:

<option value='Option21' style='font-size: 15px;'>Option21</option>
                                    <option value='Option22' style='font-size: 15px;'>Option22</option>
                                    <option value='Option23' style='font-size: 15px;'>Option23</option>

How to implement it? Help please!

JavaScript in Bootstrap 5

I’m quiet new to building webpages and just started building one with Bootstrap 5.
I want to add/remove the bootstrap class “bg-opacity” to my navbar based on viewport width and thought I can do so with JS. But the function I found is not working, cause BS doesn’t use JQuery anymore. Is there an easy way to add/remove classes that exist in Bootstrap 5?

I would be very happy about an answer.

Cheers and thanks in advance 🙂

I tried to use this function


jQuery(document).ready(function($) {
    var alterClass = function() {
      var ww = document.body.clientWidth;
      if (ww < 767) {
        $('.navbar').addClass('bg-opacity-75');
      } else if (ww >= 768) {
        $('.navbar').removeClass('bg-opacity-75');
      };
    };
    $(window).resize(function(){
      alterClass();
    });
    //Fire it when the page first loads:
    alterClass();
  });

Child routes not working with Remix 2.8.1

Repo: https://github.com/leongaban/remix-tutorial

I’m using a brand new build of Remix.

My vite.config.ts:

import { vitePlugin as remix } from '@remix-run/dev';
import { installGlobals } from '@remix-run/node';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

installGlobals();

export default defineConfig({
  plugins: [
    remix({
      ignoredRouteFiles: ['**/.*'], // <-- default without this did not work too
    }),
    tsconfigPaths(),
  ],
});

Settings component:

import { Link, Outlet } from '@remix-run/react';

export default function Settings() {
  return (
    <div>
      <h1>Settings</h1>
      <p>This is the Settings page</p>
      <nav>
        <Link to="app">App</Link>
        <br />
        <Link to="profile">Profile</Link>
        <Outlet />
      </nav>
    </div>
  );
}

settings/app component:

import { Link } from '@remix-run/react';

export default function App() {
  return (
    <div>
      <h1>App Settings</h1>
      <p>...</p>
    </div>
  );
}

Folder structure:
enter image description here

The Bug

I navigated to /settings and click on the App Link

I get a 404 Not Found Error and the following error in the Chrome console:

“Error: No route matches URL “/settings/app””

Node.js: ffmpeg command not waiting for other ffmpeg command promise to be resolved

I am trying to node.js program, in which fluent-ffmpeg first converts an input-mp4-file to an mp3 file and after that fluent-ffmpeg command should trim the mp3 file (for example only 0:12 – 0:48).
I am using promises for that but it seems like that the trimFile() method is not waiting for the promise to be resolved. I have the following code:

// data = [stream, duration, trimStartTime, res, name]
async function convertMP4ToMP3(data) {
    var name = data[4];
    let inputFilePath = `./temp/${name}.mp3`
    return new Promise((resolve, reject) => {
        ffmpeg()
            .input(`./temp/${name}.mp4`)
            .output(`./temp/${name}.mp3`)
            .audioCodec('libmp3lame')
            .on('error', reject)
            .run();
        console.log("convertMP4toMP3 DONE!n");
        resolve(data.concat([inputFilePath]));
    });
}

// data = [stream, duration, trimStartTime, res, name, inputFilePath]
async function trimFile(data) {
        console.log("trimming starting");
  return new Promise((resolve, reject) => {
      setTimeout(() => {
    let duration = data[1];
    if (duration > 0) {
    let trimStartTime = data[2];
    let inputFilePath = data[5];

    var dotIndex = inputFilePath.lastIndexOf(".");
    var outputFilePath = inputFilePath.substring(0, dotIndex) + "_t" + inputFilePath.substring(dotIndex);
   
    const trim = new ffmpeg({source: inputFilePath});
    trim
        .setStartTime(trimStartTime)
        .setDuration(duration)
        .on("start", function(commandLine) {
            console.log("Spawned ffmpeg with: " + commandLine)
        })
        .on('end', function(err) {
                if (!err) {
                    console.log('trimming Done');
                }
            })
        .on('error', function(err) {
                console.log('error in trimFile(): ', err);
            })
        .saveToFile(outputFilePath);
   
    }        
    resolve(data);
    }, "100");  // explanation underneath
    });
}

If I execute the following code:

func1(data)
        .then(func2)
        .then(convertMP4ToMP3)
        .then(trimFile)

The trimfile() method says: Invalid argument. If I change the timeout to 6000 instead of 100. It works. I was spectating the files in the filesystem and saw, that convert sometimes is not done before trimFile is executed. Can someone explain, why the trimFile() is not waiting for the resolve()?

I also tried:

// data = [stream, duration, trimStartTime, res, name]
async function convertMP4ToMP3(data) {
    var name = data[4];
    let inputFilePath = `./temp/${name}.mp3`
    return new Promise((resolve, reject) => {
        ffmpeg()
            .input(`./temp/${name}.mp4`)
            .output(`./temp/${name}.mp3`)
            .audioCodec('libmp3lame')
            .on('error', reject)
            .on('end', resolve)
            .run();
        console.log("convertMP4toMP3 DONE!n");
    });
}

But first this doesnt work neither and second thus I can not pass the string inputFilePath to the trimfile() method (because .on(‘end’, resolve(data.concat([inputFilePath]))) does not work for me).

I want to cache cloud function data in to cdn. Whatever i tried is caching in browser only

I have a webpage application developed using Flutter.
I am hosting this on Firebase hosting.
There are some data which changes over a long period of time say in 2-3 days. So I am fetching this data through Firebase cloud function.

Is there any way the data sent by the cloud function get cached to cdn? The steps that i tried so far, are caching in the browser only.

Here is firebase.json

{
  "hosting": {
    "target": "flutter",
    "public": "build/web",
    "headers": [
      {
        "source": "**",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "'public, max-age=300, s-maxage=600'"
          }
        ]
      }
    ],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      },
      {
        "source": "/fetchData/**",
        "destination": "/index.html"
      }
    ]
  }
}

and here is my cloud function

var globalData = "some global static data"
const functions = require("firebase-functions");

const cors = require("cors");

exports.fetchData = functions.https.onRequest(async (req, res) => {
  var corsFn = cors();

  await corsFn(req, res, async function () {
    var body = req.body;


    res.set("Cache-Control", "public, max-age=300, s-maxage=600");

    res.status(201).send({
      data: globalData,
    });
  });
});

with this, I am able to cache the cloud function data but only in the browser. What I want is to cache in Firebase global cdn.

How do I improve benchmark accuracy in Javascript?

I am looking for a way to benchmark the performance of a function in Javascript, so that I can optimise it more effectively. The resulting number (average tick duration) should be accurate across runs/tests, ideally no more than 2% deviation between runs, but the code I have written frequently has a deviation of more than 30%.

Here is a simplified version of my code:

let j = 0;
while (true) {
   // Collect garbage from previous run
   for (let i = 0; i < 10; i++) {
      global.gc();
   }
   
   // Reset the board state
   Board.reset();

   // Seed the random number generator
   SRandom.seed(40404040404);
   
   Board.setup();
   SERVER.setup();

   // Warm up the JIT
   for (let i = 0; i < 50; i++) {
      SERVER.tick();
   }
   
   const numTicks = 5000;
   
   const startTime = performance.now();

   for (let i = 0; i < numTicks; i++) {
      SERVER.tick();
   }

   const timeElapsed = performance.now() - startTime;
   const averageTickTimeMS = timeElapsed / numTicks;
   console.log("(#" + (j + 1) + ") Average tick MS: " + averageTickTimeMS);
   j++;
}

The code runs on node JS, and when I run it I close as many other programs as I can, typically leaving only chrome, VSCode (what I use to run the code), and a terminal open.

This does benchmark a game, so there is a lot of random number generation involved, but before the benchmark I override the built-in Math.random with a seeded random number generator (Math.random = () => SRandom.next()) and re-seed it each run.

Below is an output of when I run the benchmark:

(#1) Average tick MS: 4.773744156002999
(#2) Average tick MS: 3.103633259952068
(#3) Average tick MS: 3.431657537043095
(#4) Average tick MS: 3.3931038970351217
(#5) Average tick MS: 3.557662303030491
(#6) Average tick MS: 3.6041946840286254
(#7) Average tick MS: 3.570515029013157
(#8) Average tick MS: 3.8610670589804648
(#9) Average tick MS: 3.758602159976959
(#10) Average tick MS: 3.6722980710268023

I am not sure why the first run takes so much longer, but excluding that run there is a deviation of 24% between run 2 and run 8.

What can I do to make the benchmark more accurate? Or is this a fundamental limitation of Javascript.

Is this enough protection in the frontend?

Im currently working on auth in a mern stack project. I built a backend API which validates the JWT which the user has when trying to render a site.

Ill show some detailed infos here in “Pseudocode”:

AS SAID BEFORE THATS NOT THE REAL SYnTAX JUST THAT YOU CAN UNDERSTAND WHAT I WANT TO ACHIEVE

Backend:
server(/auth){
validateJWT
res.json("Success")
on error res.json("Unauthorized")
}

Frontend:
Useeffect({
req.server("/auth")
if(response === "Success"){
render Page
}
else{
redirect to login
}
})

So may approach was that i use the useEffect hook of react to check if the user has a valid JWT and then render the page if so and if it isn’t valid. My problem here is that i want to make sure and understand if this is save. Are there ways to edit the js files and reload the component with the edited js files? For example lets say someone doesnt have a JWT and just edits the code as followed:

Useeffect({
req.server("/auth")
if(response === "Unauthorized"){
render Page
}
else{
redirect to login
}

will this theoratically work? and if so how is it even possible to protect the frontend admin dashboard for example?

How to exclude jest/js test by tagName running with –testNamePattern?

I have a lot of tests in jest/js.
I would like to exclude some of them with tag @bug from run.

test example to exclude from run:

test("@bug Sign In - Check Wrong user credentials: status-code 400", async () => { ... });

i tried run this script:

npx jest --testNamePattern='^(?!.*@bug).*$'

but it run all tests and not exclude tests with tag @bug.

Did someone face with such behavior?

Websocket error – One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 0

I have a Node.js server running inside a Docker container. I’m trying to connect to the server using WebSockets from a web browser, but as soon as the connection is established, I get an error:

WebSocket connection to 'wss://domain/api/websockets' failed: One or more reserved bits are on: reserved1 = 1, reserved2 = 0, reserved3 = 0.

I accessed the Docker container and tried to connect using

wscat --header "Cookie:connect.sid=session-key" -c ws://127.0.0.1:5200/api/websockets

But got the error:

error: Invalid WebSocket frame: RSV1 must be clear

I should note that during the initial connection, I receive valid data packets from the server, but shortly after, the connection drops with the aforementioned error.

Here’s the code of the server:

import WebSocket, { WebSocketServer } from "ws";
import { Server } from "http";
import { sessionParser } from "../passport";
import { User } from "../../share-types";
import { events, EventsList } from "./events";

export default async (server: Server) => {
    const wsServer = new WebSocketServer({
        noServer: true,
        path: '/api/websockets',
    });
    server.on('upgrade', (request: Express.Request, socket, head) => {
        sessionParser(request, {}, () => {
            const user: User = request.session?.passport?.user;
            if (!user?.ID) return socket.destroy();
            wsServer.handleUpgrade(request as any, socket, head, (ws) => {
                wsServer.emit('connection', ws, request, user);
            });
        })
    });


    wsServer.on('connection', function (socket: WebSocket, request: Express.Request, user: User) {

        socket.on('error', console.error);
        socket.on('message', function (message) {
            try {
                message = JSON.parse(message.toString());
                events.emit(EventsList.NEW_WEB_SOCKET_MESSAGE, { user, message });
            } catch { }

        });
    });

    return wsServer;
};

WS package version:
“ws”: “^8.16.0”

What could be the issue?