Can’t transfer error from Express backend to React frontend

Quick Background

I have a React component called ‘Register.jsx’ that allows users to create a username and password. The submit button sends the information to the Express backend and a row is created in a MySQL table that stores the usernames and passwords. In MySQL, I have the ‘username’ column set to unique values only and an error for duplicate entries is generated in Express…

{
    "message": "ER_DUP_ENTRY"
}

Desired Results

I would like to display that error in the ‘Register.jsx’ component and allow them to retry it.

Current Results

I can’t seem to be able to retrieve the error message. When I hit the endpoint on Postman, I get the response, so I know the Express portion works.

Relevant Code

Register.jsx

const handleSubmit = async () => {
      try {
        const res = await createUser(username, password);
        console.log(res)
      } catch (err) {
        console.log(err);
        setError(JSON.stringify(err))
      }
    }

createUser.js

try {
        const response = await fetch('http://localhost:3001/register', {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-Type': 'application/json',
            }
        })

    } catch (error) {
        return error;
    }

index.js

app.post('/register', async (req, res) => {
      const data = req.body;
      const username = data.username;
      const password = data.password;
  
      const query = `INSERT INTO accounts (username, password, email) VALUES ('${username}','${password}');`;
      
      try {
        const result = await connection.query(query);
        const res = JSON.stringify(result)
        res.status(200).send({ message: 'success'})
      } catch (error) {
          return res.status(401).send({ message: error.code});
      }
  
  })

What I’ve Tried

I’ve tried all combination of JSON.stringify/return/console.log the caught & sent errors. I’ve tried to debug with console.log(error) to see what’s going on. I’ve made no progress in 3 – 5 hours. I’ve tried using State hooks also, but since my console.logs are blank it doesn’t really matter.

nest.js and cloudinary: problem with single image upload

I am trying to upload user’s avatar to cloudinary, so far the function looks like this:

uploadStreamFile(file: Express.Multer.File): Promise<CloudinaryResponse> {
    return new Promise<CloudinaryResponse>((resolve, reject) => {
      const uploadStream = cloudinary.uploader.upload_stream(
        (error, result) => {
          if (error) return reject(error);
          resolve(result);
        },
      );

      streamifier.createReadStream(file.buffer).pipe(uploadStream);
    });
  }

It works, but my goal is to save the image and overwrite it if user will change avatar again. In cloudinary docs I found upload function that can take my desired options, so I modified function to:

  async uploadFile(file: Express.Multer.File, userId: string) {
    console.log(`FILE: ${file}`)
    console.log(`FILE NAME ${file.filename}`)
    console.log(`ORG NAME ${file.originalname}`)
    console.log(`FIELD NAME ${file.fieldname}`)

    const uploadResponse = await cloudinary.uploader.upload(file.originalname, {
    folder: 'avatars',
    public_id: userId,
    overwrite: true, 
  });

and the output:

649439028425fb78cabf8601
FILE: [object Object]
FILE NAME undefined
ORG NAME 103_gargamel.jpg
FIELD NAME file
[Nest] 62390  - 07/01/2023, 9:33:00 PM   ERROR [ExceptionsHandler] Object:
{
  "error": {
    "errno": -2,
    "code": "ENOENT",
    "syscall": "open",
    "path": "103_gargamel.jpg"
  }
}

I think request from frontend is ok, because file and userId are passed successfully.
As first argument I tried to pass “avatar” (instead of file.originalname) or even binary buffer, but TS is expecting string there.

In case someone needs, this is the controller:

 @Post('upload/:userId')
    @UseInterceptors(FileInterceptor('file'))
    uploadImage(@UploadedFile() file: Express.Multer.File, @Param('userId') userId: string)
    {
      return this.cloudinaryService.uploadFile(file, userId);
    }

What am I missing?

JS sort() doesn’t work as expected on nested objects

I have an array of objects like below, and I would like to sort the array by value of each object.


const arr = [
        {
            0: "id1",
            1: {
                title: "object1",
                value: 200
            }
        },
        {
            0: "id2",
            1: {
                title: "object2",
                value: 100
            }
        },
        {
            0: "id3",
            1: {
                title: "object3",
                value: 300
            }
        },
    ]


//result - array I want to get as the final result of sort
sortedArr = [
        {
            0: "id3",
            1: {
                title: "object2",
                value: 100
            }
        },
        {
            0: "id2",
            1: {
                title: "object1",
                value: 200
            }
        },
        {
            0: "id3",
            1: {
                title: "object3",
                value: 300
            }
        },
    ]

I tried:

    const sortedArr = arr.sort((a, b) => {
        if (a[1].value - b[1].value) {
            return -1
        } else {
            return 1
        }             
    })

But I only get the reversed array not sorted as I wish.

I found similar problems but when I tried other solutions it didn’t work for me, or I did something wrong.

React “npm ERR! missing script: start” when running project with Docker

I get the error mentioned in the title when running my docker compose, I have no idea why. I’ve been at it for hours, literally nothing helps.

I’m following this guide

Folder structure:

Folder structure

Dockerfile:

FROM --platform=$BUILDPLATFORM node:lts AS development

WORKDIR /code
COPY package.json /code/package.json
COPY package-lock.json /code/package-lock.json

RUN npm ci
COPY . /code

ENV CI=true
ENV PORT=3000

CMD [ "npm", "start" ]

FROM development AS dev-envs
RUN <<EOF
apt-get update
apt-get install -y git
EOF

RUN <<EOF
useradd -s /bin/bash -m vscode
groupadd docker
usermod -aG docker vscode
EOF
# install Docker tools (cli, buildx, compose)
COPY --from=gloursdocker/docker / /
CMD [ "npm", "start" ]

FROM development AS build

RUN ["npm", "run", "build"]

FROM nginx:1.13-alpine

COPY --from=build /code/build /usr/share/nginx/html

compose.yaml

services:
  backend:
    build:
      context: ./tracker
      dockerfile: Dockerfile
    ports:
      - 8080:8080
    environment:
      - POSTGRES_DB=example
    networks:
      - spring-postgres
    depends_on:
      - db
  db:
    image: postgres
    restart: always
    secrets:
      - db-password
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - spring-postgres
    environment:
      - POSTGRES_DB=example
      - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
    expose:
      - 5432

  frontend:
    build:
      context: ./tracker_frontend
      dockerfile: Dockerfile
    ports:
      - 3000:3000
    volumes:
      - /project/node_modules
    networks:
      - react-spring
    depends_on:
      - backend
    expose:
      - 3306
      - 33060

volumes:
  db-data:

secrets:
  db-password:
    file: db/password.txt

networks:
  react-spring:
  spring-postgres:

package.json

{
  "name": "tracker_frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@atlaskit/inline-edit": "^12.2.12",
    "@atlaskit/textarea": "^4.5.6",
    "@atlaskit/textfield": "^5.3.7",
    "@atlaskit/theme": "^12.4.1",
    "@emotion/react": "^11.11.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.3.3",
    "formik": "^2.2.9",
    "jquery": "^3.6.3",
    "moment": "^2.29.4",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.2",
    "react-data-table-component": "^7.5.3",
    "react-data-table-component-with-filter": "^7.5.3",
    "react-dom": "^18.2.0",
    "react-dropzone": "^14.2.3",
    "react-icons": "^4.8.0",
    "react-router-dom": "^6.8.1",
    "react-scripts": "5.0.1",
    "react-select": "^5.7.3",
    "styled-components": "^5.3.9",
    "web-vitals": "^2.1.4",
    "bootstrap": "^5.2.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Tried a ton of things I found online, like replacing the package.json’s "start": "react-scripts start" with "start": node index.js, trying out a bunch of other Dockerfiles, double-checking everything, but I’ve been at this for 6+ hours now and I’m completely out of ideas.

I’m a beginner when it comes to Docker, admittedly I don’t know much about it, but I got the backend + DB to be containerized, and they are running fine, but I’m at a complete loss at this error I keep getting. Literally nothing works provided by people at different questions similar to mine.

Pixijs 7 load texture via Asset background loading

I am getting stuck on loading a texture via pixi 7 new Asset package. What I want to do is loading the ressource (png file) via asset loader. Then create a TilingSprite with the loaded ressource as texture. The following code will never finish:

  const textureFromAsset = PIXI.Texture.from(assets.tiles);
  const gridFromAsset = new PIXI.TilingSprite(textureFromAsset, 250, 250);
  app.stage.addChild(gridFromAsset);

The ressource is loaded and shown correctly by using a Sprite. How can I load textures via pixi asset loader?

A full codepen example is here

Reiniciar/eliminar postback de Ajax durante una entrada de texto [closed]

Hola tengo la siguiente pregunta y si alguien me puede ayudar con este código ajax por favor, ¿como puedo detener o terminar el postback después de que el response ya se cumplió?, explico el proceso, ¨text editor¨ durante la escritura ingreso un nombre, el sistema me devuelve una sugerencia con la opción de selección, al dar click en la sugerencia se agrega en text editor y reemplaza el ingreso, el problema es que, el postback se queda intermitente y aunque no exista coincidencia (pero si ingreso de texto) lanza repetidamente la última sugerencia, al hacer una nueva búsqueda el sistema proporciona sin problema la nueva sugerenca, pero el sistema no se reinicia o se borra el postback y continúa mostrando de nuevo repetidamente la última sugerencia ante cada keyup, que puedo hacer para terminar o reiniciar el proceso, aquí les comparto el código

main.js

var iframe = document.getElementById("editor1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

var searchTimer; // Variable to hold the timer
var xhr; // Variable to hold the AJAX request

iframeDocument.designMode = "on";

$(document).on('click', '.suggest-name', function() {
  var suggestion = $(this).text();
  var text = iframeDocument.body.innerHTML;
  var lastWord = text.split(" ").pop(); // Get the last word from the text
  var updatedText = text.replace(lastWord, suggestion); // Replace the last word with the suggestion
  iframeDocument.body.innerHTML = updatedText; // Update the iframe content
  $('.suggest-name').hide(); // Hide the suggestions
  $('.suggest-name').empty(); // Clear the suggestion text
  $('.response').empty(); // Clear the response message
  xhr = null; // Reset the AJAX request variable
});

iframeDocument.addEventListener("keyup", function() {
  try {
    var text = iframeDocument.body.innerText;
    var names = text.match(/bw{4,}b/g); // Extract all words with a minimum length of 4 characters

    if (!names) {
      $('.suggest-name').hide(); // Hide the suggestions
      return;
    }

    clearTimeout(searchTimer); // Clear the previous timer

    if (xhr) {
      xhr.abort(); // Terminate the previous AJAX request if it exists
    }

    searchTimer = setTimeout(function() {
      for (var i = 0; i < names.length; i++) {
        var name = names[i];

        // AJAX request for editor action
        xhr = $.ajax({
        url: 'includes/actions.php?timestamp=' + new Date().getTime(),
          method: 'POST',
          data: { action: 'editor', name: name },
          beforeSend: function() {
            if (xhr) {
              xhr.abort(); // Terminate the previous AJAX request if it exists
            }
          },
          success: function(response) {
            if (response.trim() !== '') {
              console.log(response);
              var suggestion = response.trim();
              $('.suggest-name').text(suggestion); // Update the suggestion text
              $('.suggest-name').show(); // Show the suggestions
              $('.response').empty(); // Clear the response message
              xhr = null; // Reset the AJAX request variable
            }
          },
          error: function(xhr, status, error) {
            console.error('AJAX request for editor action failed with error:', error);
          }
        });
      }
    }, 500); // Set a delay of 500 milliseconds before making the request
  } catch (error) {
    console.error("An error occurred:", error);
  }
});

$(document).ajaxSuccess(function(event, xhr, settings) {
  if (settings.url === 'includes/actions.php') {
    $('.response').empty(); // Clear the response message
    xhr = null; // Reset the AJAX request variable
  }
});

actions.php

elseif ($action === 'editor') {

            header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
            header("Pragma: no-cache"); // HTTP 1.0.
            header("Expires: 0"); // Proxies.


// Store the last executed search term
$lastSearchTerm = '';

if ($action === 'editor') {
    // Handle editor action
    $name = mysqli_real_escape_string($connect, $_POST['name']);

    // Check if the current search term is the same as the last one
    if ($name === $lastSearchTerm) {
        // Return an appropriate response indicating that the search is already up to date
        echo 'Already up to date.';
        return;
    }

    // Update the last search term
    $lastSearchTerm = $name;

    // Perform the SQL query to search for the last three words in the "users" table
    $sql = "SELECT * FROM users WHERE user_name LIKE '$name%'";
    $result = mysqli_query($connect, $sql);

    // Process the query result
    if (mysqli_num_rows($result) > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            // Do something with the retrieved data
            echo "User ID: " . $row['user_id'] . ", User Name: " . $row['user_name'] . "<br>";
        }
    } else {
        // echo "No users found.";
    }
}


// Close the database connection
mysqli_close($connect);


        }

Por favor les pido su ayuda para solucionar este problema, lo único que busco es borrar o terminar o reiniciar la data del response para que deje de enviar, ya intenté borrando caché pero tampoco ha servido, o si alguien sabe alguna solución que pueda funcionar, muchas gracias

How to use HTTP on CF pages for forwarding to MQTT broker without “ERR_TOO_MANY_REDIRECTS”

I have this code:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mqtt/3.0.0/mqtt.min.js"></script>
</head>
<body>
    <script>
        var urlParams = new URLSearchParams(window.location.search);
        var topic = urlParams.get('topic');
        var message = urlParams.get('message');
        var brokerUrl = urlParams.get('brokerUrl');
        var port = urlParams.get('port');

        var client = mqtt.connect('mqtt://' + brokerUrl + ':' + port);

        client.on('connect', function() {
            if (topic && message) {
                client.publish(topic, message);
            }
            client.end();
        });
    </script>
</body>
</html>

Also I have CF pages site with custom domain.

When I off SSL/TLS I always have error of too many redirects

I need use HTTP to use HiveMQ MQTT broker without error
was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://null:800/'. This request has been blocked; this endpoint must be available over WSS.

But afaik, and I tried HiveMQ cant be reachable with https.

How I said below I tried to SSL/TLS encryption to OFF.

How to use beefe/react-native-keyboard in functional component?

React native Numeric_keypad library required for numberic input only.
A another one is react-native-custom-keyboard but seems to not working in newer versions so this library is another one for the same task but without native implementation but no use case shown for the functional ones..

I tried adding all methods given for the same but with no output of working .it seems like model is not properly used as per functional context, so _notify does’nt exist error…

        </View> 
            <Keyboard 
                keyboardType="decimal-pad"
                onClear={this._handleClear.bind(this)}
                onDelete={this._handleDelete.bind(this)}
                onKeyPress={this._handleKeyPress.bind(this)}
            />
        </View>

Link for the same is https://github.com/beefe/react-native-keyboard

Save client side large set of data to local file on Chrome Android with streams

I have a code that decompiles a video and generates a new video, all on client side. As the videos are large, the output of the video muxer is directet to a writablestream, so the data is consumed as it is generated to prevent excessive memory usage. On chrome for windows, I get the writable stream with the following code:

        fileHandle = await window.showSaveFilePicker({
          startIn: 'videos',
          suggestedName: 'newSession.webm',
          types: [{
            description: 'Video File',
            accept: { 'video/webm': ['.webm'] },
          }],
        });
        fileWritableStream = await fileHandle.createWritable();

Then, I simply feed the fileWritableStream, which is an instance of FileSystemWritableFileStream to the muxer:

 muxer1 = new WebMMuxer({
          target: fileWritableStream,
          video: {
            codec: 'V_VP9',
            width: outputW,
            height: outputH,
            frameRate: FPS
          },
          audio: {
            codec: 'A_OPUS',
            numberOfChannels: 2,
            sampleRate: 48000
          }
        });

The code above works as following: When fileHandle runs, the user is prompted to save file to local disk. When he is finished, the rest of the code starts to wrtite video chunks to the stream, and this chunks are immediatly output to the file, thus preventing accumulation of the new video chunks in memory.

Now for the problem: In chrome for Android, there is no support for window.showSaveFilePicker() nor window.showDirectoryPicker(), which means I can’t prompt the user for a location to save the file and, as a consequence, I can’t instantiate a FileSystemFileHandle instance, from which I could then obtain the FileSystemWritableFileStream I need. So, is there a workaround for this situation?

What I am trying to achieve is to get a FileSystemWritableFileStream instance in chrome for android, with an underlying FileSystemDirectoryHandle pointing to a folder that the user have selected.

retriving data from Uint8 array

I have a point data in this format

Uint8Array
(1434544) [170, 189, 128, 65, 141, 54, 182, 65, 218, 50, 12, 192, 61, 247, 134, 194, 242, 169, 128, 65, ...]

It is Uint8Array and represent point data of point cloud in format of x, y, z, and i where each is 4 bytes making each point 16 bytes.

The data array is list of point in byte stream or typedarray for points

How can i transformed this data to retrive x, y, z and i of each point?

Any help please

JavaScript – Get object keys in order of declaration, including symbols

In JavaScript Reflect.ownKeys() is the only function that returns both regular keys and keys that are symbols, as far as I know of at least. Other functions–for example Object.getOwnPropertyNames()–always return the keys in the order of declaration. However, with Reflect.ownKeys() the symbols are always at the end, regardless of that order.

Consider the following example:

const symbolProperty = Symbol('symbolProperty');

const object = {

    [symbolProperty]: 'Symbol Property',
    regularProperty: 'Regular Property'

};

console.log(Reflect.ownKeys(object));

// Returns 0: "regularProperty", 1: Symbol("symbolProperty")

Is there any way I can get all keys in the predictable order of declaration, like with Object.getOwnPropertyNames()? So for my example:

// 0: Symbol("symbolProperty"), 1: "regularProperty"

Please note that this should work with any object, without a separate array keeping track of the keys, or a similar “hack.” If anyone knows how I can modify the array or of a different function to achieve the expected result it would be greatly appreciated.

I want a pop up box that will tell someone which outside website they are being directed to that will hold for 15 seconds before moving to new webpage

I currently have the code to set up with an innerHTML message. I want to turn that into a pop up that will show for 15 seconds and then open the window to the correct website. There are 6 different innerHTML messages that need to be seen depending on which website they are being directed to.
I also want it to work on mobile devices.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Leaving the Treatment Center </title>
<style>
    margin:auto;
    font-family:verdana;
</style>
    <center><label for="Zipcode">Zip Code:</label></center>
    <center><input type="text" id="Zipcode" name="Zipcode"></center>
    <p id="Zipcode_text"></p>
    <br>
    <center><button onclick="myFunction()">Find My Local Intergroup</button></center>
    <script>
        function myFunction() {
            var a = document.getElementById("Zipcode").value;
            if (a == "41310") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Bluegrass Intergroup's Website";
                // <a href="http://www.bluegrassintergroup.org/"> Bluegrass Intergroup's Website</a>;
                window.open("http://www.bluegrassintergroup.org/", 'newwindow')
       } 
       else if (a == "42101") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Bowling Green Intergroup's Webpage";
                // <a href=" http://bowlinggreenaa.org/">Bowling Green Intergroup's Webpage</a>;
                window.open(" http://bowlinggreenaa.org/", 'newwindow')
            }
        else if (a == "42070") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Western Kentucky Intergroup's Website";
                // <a href="https://wkintergroup.org/"> The Western Kentucky Intergroup's Website</a>;
                window.open("https://wkintergroup.org/", 'newwindow')
            }
        else if (a == "40202") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Greater Louisville Intergroup's Website";
                // <a href="https://www.loukyaa.org/"> Greater Louisville Intergroup's Website</a>;
                window.open("https://www.loukyaa.org/", 'newwindow')
        }
        else if (a == "41063") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Northern Kentucky Intergroup's Website";
                // <a href="https://www.nkyaa.info/"> The Northern Kentucky Intergroup's Website</a>;
                window.open("https://www.nkyaa.info/", 'newwindow')
        }
        else if (a == "42343") {
                document.getElementById("Zipcode_text").innerHTML = "Thank you. You will be directed to the Owensboro-Yellowbanks Intergroup's Website";
                // <a href="https://www.area26.net/wp/owensboro-yellowbanks-central-office/"> The Owensboro-Yellowbanks Intergroup's Website</a>;
                window.open("https://www.area26.net/wp/owensboro-yellowbanks-central-office/", 'newwindow')
        }
       else {
                document.getElementById("Zipcode_text").innerHTML = "I'm sorry but we have not found a local Intergroup that covers that area. Please feel free to reach out to another intergroup to help connect to Alcoholics Anonymous in Kentucky, Southern Indiana and Ohio.";
                // <a href="https://www.area26.net/wp/local-intergroups/"> Area 26 Find A Meeting Page</a>;
                window.open("https://www.area26.net/wp/local-intergroups/", 'newwindow')
            }
        }
    </script>
</body>
</html>

Plotly JS stacked percent barchart with independent data in each bar

I’m using Plotly JS to draw a percent stacked bar chart where each “element” of each “bar” is totally independent from the elements of the other bars. Each bar may have a different number of elements. There may be many bars (e.g. 200), and each bar may have many elements (e.g. 50). The color of each element must be set independent from the color of any other element.

To be clear, the following image explains what I mean by “bar” and “element”:

Definitions

See this codepen for a fully functional implementation of this.

The problem I’m having is with performance and memory consumption for a larger number of bars. In the above codepen, if you change the first line

const NUM_BARS = 50;

so that there are, say, 200 bars instead of 50, then you will observe the performance degradation.

I suspect the performance is poor because I am using Plotly JS’s percent stacked bar chart in a somewhat unnatural way: each element is a separate trace, so there are tons of
traces for Plotly to handle.

I’m hoping someone can help me with either or both of the following questions: (1) Is there
a better (more performant) way to construct this plot using Plotly JS than how I’m doing it
in the above codepen? (2) Is there another JavaScript plotting library that would allow me
to construct this type of plot with better performance?