Uploading an excel file into ExcelJS then downloading causes the file to be corrupted

I’m writing a NextJS app that uploads an excel document (.xlsx), changes some rows, then allows the user to download the amended version.

I am testing out the upload/download functionality, and while the upload/download happens with the code below – the downloaded file is corrupted but the same size. It cannot open properly.

I am stuck and open to help.

Thanks.

/api/doupload/route.js:

import { NextRequest, NextResponse } from 'next/server'
import ExcelJS from 'exceljs';

export async function POST(req) {

    try
    {
        const data = await req.formData();

        const file = data.get('file');

        const workbook = new ExcelJS.Workbook();

        const bytes = await file.arrayBuffer()
        const buffer = Buffer.from(bytes)

        await workbook.xlsx.load(buffer); // Load from buffer

        const dbuffer = await workbook.xlsx.writeBuffer(); // Get the modified data as a buffer
        const filename = 'modified_spreadsheet.xlsx';

        const res = new NextResponse(dbuffer, {
            status: 200,
            headers: ({
                "content-disposition": 'attachment; filename='+filename,
                "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            })
          })
          return res;
        }
    }
    catch(e)
    {
        return NextResponse.json({"a": "0", "b": e.message})
    }
}

Main.jsx:

const MainLoggedIn = () => {

const [downloadUrl, setDownloadUrl] = useState(null);

async function doit()
{
    try
    {
        const formData = new FormData();
        formData.set('file', selectedFile);
        //SelectedFile is an input type="File" button and is e.target.files[0]

        const configuration = {
            method: "POST",
            url: '/api/doupload',
            withCredentials: true,      // needed to stop CORS errors
            data: formData
        };

        const response = await axios(configuration)

        const modifiedSpreadsheetBlob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // Create a URL for the blob
        const modifiedSpreadsheetUrl = URL.createObjectURL(modifiedSpreadsheetBlob);

        setDownloadUrl(modifiedSpreadsheetUrl);
    }
    catch(err)
    {
        console.log("ERROR: "+err.message);
    }

    return (
    <p>
        <a href={downloadUrl} download="modified_spreadsheet.xlsx">
            Click here to download the modified spreadsheet
        </a>
        </p>
    )
};

export default MainLoggedIn;

Getting an empty array from zustand store

I am trying get the fetched array from the zustand store, but it’s returned as empty.

script.jsx

const store = Zstore();

const params = useParams();

useEffect(() => {
    store.fetchStock(params.id);
}, []);


console.log(store.stock); // Empty array

Zstore.js

import { create } from 'zustand';
import axios from 'axios';

const Zstore = create((set) => ({
    stock: [],

    fetchStock: async (id) => {
    
        const res = await axios.get('http://127.0.0.1:8000/searchList/')
        const stock = res.data.filter((stock) => stock.symbol == id.toUpperCase()).map((stock) => {
            return {
                symbol: stock.symbol,
                name: stock.name,
            }
        });
        set({stock});
                console.log(stock); // Array not empty
    },
}));

export default Zstore;

I did attempt to add store.stock.length as a dependency to the useEffect but to no avail.

npm package ‘ultimate-text-to-image’ shows Invalid File Error

const url = "https://i.imgur.com/EP7lGGu.jpg";
const buffer = new UltimateTextToImage("repeatX").render().toBuffer();
const base64 = new UltimateTextToImage("fitY").render().toBuffer().toString("base64");
const arrayBuffer = new Uint8Array(new UltimateTextToImage("repeat").render().toBuffer());

// images
const canvasImage1 = await getCanvasImage({url});
const canvasImage2 = await getCanvasImage({base64});
const canvasImage3 = await getCanvasImage({buffer});
const canvasImage4 = await getCanvasImage({arrayBuffer});

The above is from docs of the npm package ultimate-text-to-image. Trying images from own file-system, filePath, Buffer or base64, shows error Invalid File. Any solutions.

How can I access the values in this array?

I am trying to access the value inside of an array but console keeps coming back as undefined. The array does exist and it is populated as shown by console. Issue occurs when I make reference to anything inside of the array.

this.comments$.subscribe({next:(value) => this.a_s.squad.push(value[0])});

When i console log the array

console.log(this.a_s.squad)

This is the console message
Image from console.log(this.a_s.squad)

That works fine now as we can tell the array does exist and it contains 1 object with an index of 0

Now If I am to console log this

console.log(this.a_s.squad[0])

It comes back as undefined
Object as undefined

This is a hindrance because I won’t be able to access, sport_event_status object in the array, since if I

console.log(this.a_s.squad.sport_event_status) 

I get a message stating that this does not exist on type any[]

Now if i go back to adding [0]”The index”

console.log(this.a_s.squad[0].sport_event_status) 

The message error in the code no longer exist, but in the console I get this error

Console Error

Why is this happening ?

Button not being animated

Stuck on this problem for 2 days, Whenever i click a button in the top bar, it doesnt get animated. its width should increase and its left-border-color should turn green. however that isnt whats happening. I am using svelte and i am really new to it so the code quality is powerpoint quality.
The Code:

<script lang="ts">
  export let name;

  function onTopBarBtnClick(tab) {
        let tabButton = document.getElementsByClassName('topbarbtn ' + tab)[0]
        tabButton.classList.add('selected')
  }
</script>

<main>
  <nav class='topbar'>
    <label class="websitenameinfo">{name}</label>

    <button on:click={() => onTopBarBtnClick('1')} class="topbarbtn 1">Servers</button>
    <button on:click={() => onTopBarBtnClick('2')} class="topbarbtn 2">Events</button>
    <button on:click={() => onTopBarBtnClick('3')} class="topbarbtn 3">Store</button>
    <button on:click={() => onTopBarBtnClick('4')} class="topbarbtn 4">Info</button>
  </nav>
</main>

<style>
    .topbar {
        position: absolute;
        width: 100vw;
        height: 8vh;
        top: 0vh;
        left: 0vw;
        background-color: #1c1c1c;
        box-shadow: 1vh 1vh 2.8vh rgba(28, 28, 28, 0.8);
    }
    .websitenameinfo {
        position: absolute;
        top: 1vh;
        left: 1vw;
        text-transform: uppercase;
        font-family: Tahoma;
        font-size: 4.7vh;
        background: -webkit-linear-gradient(#2071cd, #0ac7ba);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      text-shadow: 0px 0px 3vh #579dffb3;
        font-weight: 800;
    }
    .topbarbtn {
        width: 10.1vw;
        height: 8vh;
        float: right;
        border-radius: 0px;
        background: -webkit-linear-gradient(#20cd31, #0ac7ba);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      text-shadow: 0px 0px 3vh #15ffbd5e,
                                 0px 0px 1.5vh #1573ff66;
        font-weight: 600;
        font-family: Tahoma;
        font-size: 3.8vh;
        border-image: linear-gradient();
        border-width: 0px;
        border-left-width: 0.1vw;
        border-color: rgb(45, 45, 45);
        color: rgb(52, 52, 52);
        vertical-align: top;
    transition: all 0.3s cubic-bezier(0.075, 0.82, 0.3, 1);
    }
    .selected {
            border-color: #0af05e;
            width: 15vw;
            border-left-width: 0.27vw;
            text-shadow: 0px 0px 3vh #6fffd6da, 0px 0px 1.6vh #84ff106d;
    }
</style>

I tried basically all i could search on the internet, nothing worked. i expected the buttons width to expand and the left border color to turn green. however instead what happens is, clicking on it does ABSOLUTELY nothing for some reason. ig its a issue with how i am adding ‘selected’ to the classlist but i am not sure.

Hydration failed because the initial UI does not match what was rendered on the server

I am trying to get window width and height at load and on resize; however, I get the following error. I do not see anything out of the ordinary with the html of the file.

Error: Hydration failed because the initial UI does not match what was rendered on the server.

Warning: Expected server HTML to contain a matching <div> in <div>.

See more info here: https://nextjs.org/docs/messages/react-hydration-error

Component Stack

div

div

NavHeader

./app/components/NavHeader.js (24:107)

body

html


NavHeader.js

'use client';
import Link from 'next/link'
import styles from 'styles/NavHeader.module.css'
import DensityMediumIcon from '@mui/icons-material/DensityMedium';
import { useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { auth } from "@/firebase";

export default function NavHeader() {
  const [user, loading, error] = useAuthState(auth);

  const [device, setDevice] = useState("");

  if (typeof window !== "undefined") {
    if (window.innerWidth < 1000) {
      if (device !== "small") {
        setDevice("small");
      }
    } else {
      if (device !== "desktop") {
        setDevice("desktop");
      }
    }
  }


  const clickHandler = () => {
    const x = document.getElementById("menuMobile");
    if (x.style.display === "flex") {
      x.style.display = "none";
    } else {
      x.style.display = "flex";
    }
  }

  if (typeof window !== "undefined") {
    let w = window.innerWidth;


    window.addEventListener("resize", function () {
      let w = window.innerWidth;
      if (w < 1000) {
        setDevice("small");
      } else {
        setDevice("desktop");
      }
    })
  }

  return (
    <div className={styles.headerContainer}>
      <div className={styles.logo} />
      {(device === "desktop") &&
        <div id={"desktopMenu"} className={styles.desktopMenu}>
          <Link href={"/"}>HOME</Link>
          <Link href={"/about"}>ABOUT US</Link>
          <Link href={"/electricity"}>ELECTRICITY</Link>
          <Link href={"/pool-heating"}>POOL HEATING</Link>
          <Link href={"/contact-us"}>CONTACT US</Link>
          {user && <Link href={"/dashboard"} className={styles.signIn}>DASHBOARD</Link>}
          {!user && <Link href={"/sign-in"} className={styles.signIn}>CUSTOMER LOGIN</Link>}
        </div>
      }
      {(device === "small") &&
        <div>
          <DensityMediumIcon id={"menuIcon"} onClick={clickHandler} className={styles.expand} />
          <div id={"menuMobile"} className={styles.menuMobile}>
            <Link href={"/"} onClick={clickHandler}>HOME</Link>
            <Link href={"/about"} onClick={clickHandler}>ABOUT US</Link>
            <Link href={"/electricity"} onClick={clickHandler}>ELECTRICITY</Link>
            <Link href={"/pool-heating"} onClick={clickHandler}>POOL HEATING</Link>
            <Link href={"/contact-us"} onClick={clickHandler}>CONTACT US</Link>
            {user && <Link href={"/dashboard"} onClick={clickHandler}>DASHBOARD</Link>}
            {!user && <Link href={"/sign-in"} onClick={clickHandler}>CUSTOMER LOGIN</Link>}
          </div>
        </div>
      }
    </div>
  )
}

I am using Next.js v14.1.0. Any help would be much appreciated.

why am i getting an error even if i have the latest verison of react and there is no logical error [duplicate]

i was learning react and this was the first file that i had started with
in that i tried entering another div and tried with <>

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <>
      <h1>this is me</h1>
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
      </>
    );
  }
}

this was the code that i had
but the moment i used<> it became an error

rror in ./src/App.js
Syntax error: Unexpected token (7:7)

   5 |   render() {
   6 |     return (
>  7 |       <>
     |        ^
   8 |       <h1>this is me</h1>
   9 |       <div className="App">
  10 |         <div className="E

what should i do to get rid of this?

Validating CPF on front-end with JavaScript and JQuery

It’s a very unusual thing but…
Intent to change a class of an element when its value matches with a rule by keyup/onchange/input event (all of these already tried).
Have this

$(document).ready(function() {
                        $('#cpf').on('keyup', function() {
                            var element = $('#cpf');
                            var val = element.val();
                            let cpfValue = val.replace(/D/g, "");
                            var result = validateCpf(cpfValue);
                            console.log('RESULT: ', result);
                            if (result==1) {
                                $('#cpf').addClass('is-valid');
                            } else {
                                $('#cpf').addClass('is-invalid');
                            }
                        });
                        //validateCpf(string) 
                        function validateCpf(param) {
                            var strToMatch = param;
                            let total = 0;
                            let factor;
                            let x;

                            function gear(str, flag) {
                                if (!flag) {
                                    var substr = str.substring(0, 9);
                                    x = valDig(substr);
                                    console.log('match?: ', x == strToMatch.substr(9, 1))
                                    if (x == strToMatch.substr(9, 1)) {
                                        var substr = str.substring(0, 9) + str.substr(9, 1);
                                        gear(substr, true);
                                    } else {
                                        return false;
                                    }
                                } else {
                                    var substr = str;
                                    x = valDig(substr, true);
                                    console.log('match2? :', x == strToMatch.substr(10, 1));
                                    if (x == strToMatch.substr(10, 1)) {
                                        console.log('It worked!');
                                        return 1;
                                    } else {
                                        console.log('no valid');
                                        return false;
                                    }
                                }

                                function valDig(str, flag) {
                                    flag ?
                                        factor = 11 :
                                        factor = 10;
                                    total = 0;
                                    minhaString = str;
                                    for (let i = 0; i < minhaString.length; i++) {
                                        total += parseInt(minhaString.charAt(i)) * factor;
                                        factor--;
                                    }
                                    var rest = total % 11;
                                    if (rest == 10) {
                                        x = 0;
                                    } else {
                                        x = Math.abs(11 - rest);
                                    }
                                    return x;
                                }
                            }
                            console.log(param.length);
                            if (param.length == 11) {
                                gear(param)
                            } else {
                                return false;
                            }
                        }
                    })
<input id="cpf" class="form-control @error('cpf') is-invalid @enderror" type="text"
                        name="cpf" value="@error('cpf') {{''}} @else {{ old('cpf') }} @enderror"
                        placeholder="@error('cpf') Insira um número de CPF válido. @enderror" />

The validating itself is already done, but the function, curiosly, returns ‘undefined’ when it matches, while ‘false’ when it doesn’t, as you can see from the console logs below:

8
(índice):96 RESULT:  false
(índice):153 9
(índice):96 RESULT:  false
(índice):153 10
(índice):96 RESULT:  false
(índice):153 11
(índice):114 match?:  true
(índice):124 match2? : true
(índice):126 It worked!
(índice):96 RESULT:  undefined

The last occurence refers to the console.log('match?: ', x == strToMatch.substr(9, 1)), which is just executed when length of the string matches 11 (once it’s a dinamic change).

Any helps will be well come.

Error to test a call function onClick react

I have the following component and the following test. This test is failing even though the function was mocketed. I’d like know how I should fix it. “@testing-library/react”: “^14.2.1” and “react”: “^18.2.0”.

import { useCalculator } from "./hooks/useCalculator";

export const CalculatorApp = () => {
  const { displayNumber, operation, display, answer, reset } = useCalculator();

  return (
    <>
      <div className="container">
        <p>Calculator - React</p>
        <div className="calculator">
          <div aria-label="display">{displayNumber}</div>

          <div className="calculator__keys">
            <button
              onClick={() => operation("addition")}
              aria-label="addition"
            >
              +
            </button>
            ...
            <button aria-label="seven" onClick={() => display(7)}>7</button>
            ...
          </div>
        </div>
      </div>
    </>
  );
}

TEST

import { fireEvent, render, screen } from "@testing-library/react";
import { CalculatorApp } from "../src/CalculatorApp.jsx";

describe("Component test <CalculatorApp/>", () => {

  const mockOperation = jest.fn();

  beforeEach(() => jest.clearAllMocks());

  test("should call a matematical operation", () => {
    render(<CalculatorApp />);

    const selectedOperation = screen.getByLabelText("addition");
    fireEvent.click(selectedOperation);

    expect(mockOperation).toHaveBeenCalled();
    expect(mockOperation).toHaveBeenCalledWith("addition");
  });
});

Spring Boot – Security – Websocket – Cannot load webjars / resource blocked due to MIME type (“”) mismatch errors

I’m using Spring Boot, Spring Security, Thymeleaf, Websockets.

I have the following dependencies in pom.xml:

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>sockjs-client</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>stomp-websocket</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.1.1-1</version>
        </dependency>

In an html file, I have the following references:

  <link href="/webjars/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <script src="/webjars/jquery/jquery.min.js"></script>
  <script src="/webjars/sockjs-client/sockjs.min.js"></script>
  <script src="/webjars/stomp-websocket/stomp.min.js"></script>

I have also tried placing the jars in the same directory as the html file like this:

<link href="bootstrap.min.css" rel="stylesheet" type="text/css">
<script src="jquery.min.js" type="text/javascript"></script>
<script src="sockjs.min.js" type="text/javascript"></script>
<script src="stomp.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>

My SecurityFilterChain:

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.csrf().disable().authorizeHttpRequests()


                .requestMatchers("/register").permitAll()
                .requestMatchers("/websocket").permitAll()
                .requestMatchers("/home").permitAll().and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/websocket", true).permitAll()
                .and()
                .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout").permitAll();

        return http.build();
    }

When the html page tries to load, I keep getting the following errors (which are found in the browser’s console):

The resource from “http://localhost:8080/bootstrap.min.css” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
The resource from “http://localhost:8080/jquery.min.js” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
The resource from “http://localhost:8080/sockjs.min.js” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
The resource from “http://localhost:8080/script.js” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
The resource from “http://localhost:8080/stomp.min.js” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
Loading failed for the <script> with source “http://localhost:8080/jquery.min.js”. websocket:7:56
Loading failed for the <script> with source “http://localhost:8080/sockjs.min.js”. websocket:8:56
Loading failed for the <script> with source “http://localhost:8080/stomp.min.js”. websocket:9:55
The resource from “http://localhost:8080/script.js” was blocked due to MIME type (“”) mismatch (X-Content-Type-Options: nosniff).
websocket
Loading failed for the <script> with source “http://localhost:8080/script.js”.

I have spent hours trying to figure out what to do to get around this. I would really appreciate it if someone can shed some light on this issue!

Thanks

How to auto-populate the edit form in PHP using jQuery and AJAX?

The code is okay because it was able get a success message in the console, however, the data in the input fields is not auto populating even there is no error. I’m using jquery-3.6.0.min.js. Here’s the code:

$(document).on('click', '.editResident', function() {

    var resident_id = $(this).val();
            
            $.ajax({
                type: "GET",
                url: "code.php?resident_id=" + resident_id,
                success: function (response) {

                    console.log("Response received:", response);
                    var res = jQuery.parseJSON(response);
                    if(res.status == 404) {

                        alert(res.message);
                    }else if(res.status == 200){
                        var data = res.data;
                        $('#resident_id').val(data.ID);
                        $('#status').val(data.status);
                        $('#firstName').val(data.first_name);
                        $('#middleName').val(data.middle_name);
                        $('#lastName').val(data.last_name);
                        $('#gender').val(data.gender);
                        $('#civilStatus').val(data.civil_status);
                        $('#birthdate').val(data.birth_date);
                        $('#address').val(data.address);
                        $('#contactNum').val(data.contact_num);
                        $('#voter').val(data.voter);
                        $('#category').val(data.category);
                        $('#editResidentModal').modal('show');

                        $('#editResidentModal').on('shown.bs.modal', function (e) {
                            console.log("Edit Resident Modal is shown");
                        });
        
                        // Show the edit modal after populating fields
                        $('#editResidentModal').modal('show');
                    }
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText);
                    alert('Error occurred while fetching resident data. Please try again.');
                }
            });
});

I tried different methods but isn’t successful. I was expecting that when I click the edit button the corresponding data will auto-populate the edit form (each input fields). Here’s the PHP server side:

if (isset($_GET['resident_id'])) {
    $resident_id = mysqli_real_escape_string($conn, $_GET['resident_id']);

    $query = "SELECT * FROM resident_db WHERE ID='$resident_id'";
    $query_run = mysqli_query($conn, $query);

    if (mysqli_num_rows($query_run) == 1) {
        $resident = mysqli_fetch_array($query_run);

        $res = [
            'status' => 200,
            'message' => 'Data Fetch Successfully by id',
            'data' => $resident
        ];
        echo json_encode($res);
        return;
    } else {
        $res = [
            'status' => 404,
            'message' => 'Resident Id Not Found'
        ];
        echo json_encode($res);
        return;
    }
}

Session timeout countdown using Webworkers vs setTimeout or setInterval

I want to detect a users inactivity and kill the session.So far I’ve been using setTimeout,setInterval,and using a timestamp which has failed. I want to impliment it in **webworkers ** and still use setTimeout or setInterval and I’m hoping that the countdown will be accurate? Is there otherways to impliment this or are webworkers the way to go and will it be reliable?

I just want to accurately call a function on a set countdown or an interval.