How Can I Make My HTML Page Upload a PDF to my ASPX Page

Background

Application/Program: Lightweight Website (40,000 HTML Pages | 5 ASPX Pages)
Goal: HTML Functionality that sends Uploaded PDFs to an ASPX Page (for processing)
Problem: Uploaded PDFs Get Corrupted
Desire: Uncorrupted PDF Uploads


Tech Specs

Server Architecture: IIS 8.0 (Prod) | IIS 10.0 (Dev)
Client-Side: HTML; Javascript (Vanilla); AJAX
Server-Side: ASPX; Visual Basic
Connection/Communication: One Server/Domain (ie, the HTML pages are on the same website as the ASPX page)


Details

On my HTML page, I have a FileUpload control. I want website visitors to use that control to upload PDFs. I want to store those uploaded PDFs [directly] onto my server (in an actual directory).

To accomplish that, I want my HTML pages to “send” the users’ uploaded PDFs to my ASPX page. Whereby my ASPX page will perform the file storage.

Unfortunately, these uploaded PDFs end up getting corrupted [upon server storage]. They get corrupted in the following ways:

  1. The Uploaded PDFs Cannot Be Opened (typical error); or
  2. The Uploaded PDFs are missing content (eg, no text/image/content whatsoever; missing metadata).

Code

HTML Page

<form>
  <label for="inptFl" id="inptLbl"></label>
  <input type="file" name="inptFlNm" id="inptFl" accept=".pdf, application/pdf" multiple onchange="PickFiles();" />
  <button type="button" onclick="PushToServer();" >Submit</button>
</form>

Javascript

function PickFiles() {
  const flLst = document.getElementById("inptFl").files;
  var otPtLbl = document.getElementById("inptLbl");
  const flRdr = new FileReader();

  flRdr.addEventListener("load", (evnt) => {
    otPtLbl.setAttribute("data-loadedSource", evnt.target.result);
  });

  flRdr.ReadAsDataURL(flLst[0]);
  //flRdr.readAsBinaryString(flLst[0]);
}

function PushToServer() {
  const ajaxObj = new XMLHttpRequest();
  let otPtLbl = document.getElementById("inptLbl");
  let datURL = otPtLbl.getAttribute("data-loadedSource");

  ajaxObj.open("POST", "/WriteHere.aspx", true);
  //ajaxObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
  ajaxObj.send(datURL);
  //ajaxObj.send(encodeURIComponent(datURL));
}

ASPX Code-Behind (VB.net)

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

  Request.InputStream.Position = 0
  Dim strm = Request.InputStream
  Dim n = CInt(strm.Length)
  Dim arrStrm() As Byte
  ReDim arrStrm(n)

  Dim strmRd = strm.Read(arrStrm, 0, n)

  IO.File.WriteAllBytes("/Foldy/Filey.pdf", arrStrm)

End Sub

Troubleshooting

I’ve spent the past 3 days trying to solve this problem. My troubleshooting has included – but has not been limited to – the following:

  1. Using different JS permutations of FileReader().readAsDataURL()
  2. Using different JS permutations of FileReader().readAsBinaryString()
  3. Using different JS permutations of FileReader().readAsArrayBuffer()
  4. Using different JS permutations of enctype=multipart/form-data
  5. Using different JS permutations of enctype=application/x-www-form-urlencoded
  6. Using different JS permutations of enctype=application/pdf; charset=x-user-defined-binary
  7. Using different JS permutations of enctype=encodeURIComponent
  8. Using different VB permutations of Request.InputStream.Position
  9. Using different VB permutations of Request.InputStream.Read()
  10. Using different VB permutations of Request.InputStream.ReadASync()
  11. Scouring the web for help (especially StackOverflow.com)
  12. Glancing into technology manuals (eg, The Complete Reference to IIS 6)

Request

May you please help me get my HTML-to-ASPX file upload functionality to work for uploaded PDFs?

Thank You

Failed to resolve import “react-awesome-loaders” from “src/App.jsx”. Does the file exist?

error on the terminal

I am getting the following error: Failed to resolve import “react-awesome-loaders” from “src/App.jsx”. Does the file exist?

I have tried deleting node modules and npm i again as well as npm i react-awesome-loaders

Here is my vite-config.js file:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: [{ find: "@", replacement: resolve(__dirname, "./src") }],
  },
  server: {
    fs: {
      cachedChecks: false,
    },
  },
});

The error randomly popped up. It was working yesterday

This is the app.jsx:

import { useState, useEffect, useRef } from "react";
import "./App.css";
import { BackgroundBeams } from "./components/ui/background-beams";
import { FlipWords } from "./components/ui/flip-words";
import { BoltLoader } from "react-awesome-loaders";
import {} from "react-awesome-loaders";
import Avatars from "./components/Avatars";
import { Compare } from "./components/ui/compare";

this is my package.json:

{
  "name": "dreambooth",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  },
  "dependencies": {
    "@tabler/icons-react": "^3.24.0",
    "@tsparticles/engine": "^3.7.1",
    "@tsparticles/react": "^3.0.0",
    "@tsparticles/slim": "^3.7.1",
    "clsx": "^2.1.1",
    "framer-motion": "^11.13.1",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "tailwind-merge": "^2.5.5"
  },
  "devDependencies": {
    "@eslint/js": "^9.15.0",
    "@types/react": "^18.3.12",
    "@types/react-dom": "^18.3.1",
    "@vitejs/plugin-react": "^4.3.4",
    "autoprefixer": "^10.4.20",
    "eslint": "^9.15.0",
    "eslint-plugin-react": "^7.37.2",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.14",
    "globals": "^15.12.0",
    "postcss": "^8.4.49",
    "tailwindcss": "^3.4.16",
    "vite": "^6.0.1"
  }
}

how to get class instance in .js using edge.js

Threre is a named MyNamespace::Namespace::SubNamespace namespace, and a ClassName under the MyNamespace::Namespace::SubNamespace named ClassA, and get constructor of ClassA, like ‘ClassA^ cls = gcnew ClassA();’

in .js

        assemblyFile: dllPath,
        typeName: "MyNamespace.Namespace.SubNamespace.ClassA",
        methodName: null
      })

or

const classAapi = edge.func({
        assemblyFile: dllPath,
        typeName: "MyNamespace.Namespace.SubNamespace.ClassA",
        methodName: ClassA
      })

let classA = classAapi()

and i got a error:
“System.InvalidOperationException: Unable to access the CLR method to wrap through reflection. Make sure it is a public instance method.

Nodemon: unable to run executable: “node”

I have installed nodemon on my pc, but while executing nodemon index.js command I am getting the following error: ( the code in file runs fine on node index.js command)

nodemon index.js
[nodemon] 3.1.7
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting node index.js
[nodemon] Error
at Bus.<anonymous> (C:UsershpAppDataRoamingnpmnode_modulesnodemonlibnodemon.js:162:25)
at Bus.emit (node:events:536:35)
at ChildProcess.<anonymous> (C:UsershpAppDataRoamingnpmnode_modulesnodemonlibmonitorrun.js:180:9)
at ChildProcess.emit (node:events:524:28)
at ChildProcess._handle.onexit (node:internal/child_process:291:12)
at onErrorNT (node:internal/child_process:483:16)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21)
[nodemon] unable to run executable: “node”

I tried :
1. reinstalling Nodemon
2. reinstalling Node
3. checking path of node and nodemon (both are correct)
4. to run nodemon with explicit node path.
5. clearing npm cache.

Getting BigInt error while trying to implement a sendtransaction function

I am working on a browser extension and using the following library bitgo/utxo

It works fine if I am running it in a standalone nodejs file as .cjs.

However the same version is not working in my extension and I get this when trying to broadcast or send a transaction. I am not using BigInt

popup-C6KK9KIe.js:143 Error in sendCurrency: 
TfPropertyTypeError$1 {__error: Error
    at new TfTypeError$1 (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6…, __label: undefined, __property: 1, __value: BigInteger$c, __type: ƒ, …}
message
: 
(...)
__error
: 
Error at new TfTypeError$1 (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:33:35203) at typeforce$r (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:33:40499) at chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:33:39932 at Array.every (<anonymous>) at n (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:33:39901) at typeforce$r (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:33:40477) at Object.u [as sign] (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:140:26211) at z.sign (chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:140:28920) at chrome-extension://nldfncijlaejkdligmcipjjdoiofebbl/assets/popup-C6KK9KIe.js:140:96853 at Array.some (<anonymous>)
__label
: 
undefined
__property
: 
1
__type
: 
ƒ n(a)
__value
: 
BigInteger$c {0: 27361497, 1: 25403224, 2: 23083264, 3: 32460220, 4: 3035594, 5: 30708269, 6: 30737434, 7: 37815774, 8: 56736249, 9: 806082, t: 10, s: 0}
__valueTypeName
: 
undefined
stack
: 
(...)
get message
: 
ƒ ()
get stack
: 
ƒ ()
[[Prototype]]
: 
Error

This is the code for transaction.js

import * as bitcoin from '@bitgo/utxo-lib';

// Network configuration for Verus
const NETWORK = bitcoin.networks.verustest;
const { ECPair, TransactionBuilder } = bitcoin;

/**
 * Send currency from one address to another
 * @param {string} fromAddress - Sender's address
 * @param {string} toAddress - Recipient's address
 * @param {number} amount - Amount to send (in VRSCTEST)
 * @param {string} privateKeyWIF - Sender's private key in WIF format
 * @param {string} currency - Currency to send (default: 'VRSCTEST')
 * @returns {Promise<{txid: string}>}
 */
export async function sendCurrency(fromAddress, toAddress, amount, privateKeyWIF, currency = 'VRSCTEST') {
    try {
        console.log('Starting sendCurrency with params:', { fromAddress, toAddress, amount, currency });
        
        // Validate private key format
        if (!privateKeyWIF) {
            throw new Error('Private key is required');
        }

        // Validate that the private key is in WIF format
        let keyPair;
        try {
            keyPair = ECPair.fromWIF(privateKeyWIF, NETWORK);
        } catch (error) {
            console.error('Invalid private key:', error);
            throw new Error('Invalid private key format. Must be in WIF format.');
        }

        // Convert amount to satoshis
        const SATS_PER_COIN = 100000000;
        const satoshiAmount = Math.floor(amount * SATS_PER_COIN);
        console.log('Amount in satoshis:', satoshiAmount);
        
        // Step 1: Fetch UTXOs
        console.log('Fetching UTXOs for address:', fromAddress);
        const utxos = await makeRPCCall('getaddressutxos', [{
            addresses: [fromAddress],
            currencynames: true
        }]);
        
        if (!utxos || utxos.length === 0) {
            throw new Error('No UTXOs available');
        }

        console.log('Raw UTXOs:', JSON.stringify(utxos, null, 2));
        console.log('Found UTXOs:', utxos.length);

        // Filter UTXOs with VRSCTEST balance
        const relevantUtxos = utxos.filter(utxo => utxo.satoshis > 0);
        console.log('Relevant UTXOs:', JSON.stringify(relevantUtxos, null, 2));
        console.log('Relevant UTXOs for currency:', relevantUtxos.length);

        if (relevantUtxos.length === 0) {
            throw new Error(`No UTXOs available for ${currency}`);
        }

        // Build transaction
        const txBuilder = new TransactionBuilder(NETWORK);
        
        // Set version for Overwinter support
        txBuilder.setVersion(4);
        txBuilder.setVersionGroupId(0x892f2085);

        // Add all inputs
        let runningTotal = 0;
        for (const utxo of relevantUtxos) {
            txBuilder.addInput(utxo.txid, utxo.outputIndex);
            runningTotal += Number(utxo.satoshis);
        }

        // Calculate fee
        const fee = 20000; // 0.0002 VRSC fee
        
        if (runningTotal < satoshiAmount + fee) {
            throw new Error(`Insufficient funds. Required: ${(satoshiAmount + fee) / SATS_PER_COIN} ${currency}, Available: ${runningTotal / SATS_PER_COIN} ${currency}`);
        }

        // Add recipient output
        txBuilder.addOutput(toAddress, satoshiAmount);

        // Calculate and add change output
        const changeAmount = runningTotal - satoshiAmount - fee;
        if (changeAmount > 546) { // Dust threshold
            txBuilder.addOutput(fromAddress, changeAmount);
            console.log('Change output added:', changeAmount / SATS_PER_COIN, currency);
        }

        // Sign all inputs
        for (let i = 0; i < relevantUtxos.length; i++) {
            txBuilder.sign(
                i,
                keyPair,
                null,
                bitcoin.Transaction.SIGHASH_ALL,
                Number(relevantUtxos[i].satoshis)
            );
        }

        // Build and serialize the transaction
        const tx = txBuilder.build();
        const serializedTx = tx.toHex();
        console.log('Transaction built and serialized');

        // Broadcast transaction
        console.log('Broadcasting transaction...');
        const txid = await makeRPCCall('sendrawtransaction', [serializedTx]);
        
        console.log('Transaction broadcast successful. TXID:', txid);
        return { txid };
    } catch (error) {
        console.error('Error in sendCurrency:', error);
        throw error;
    }
}

/**
 * Estimate transaction fee
 * @param {string} fromAddress - Sender's address
 * @param {number} amount - Amount to send
 * @param {string} currency - Currency to send
 * @returns {Promise<number>} Estimated fee in VRSCTEST
 */
export async function estimateFee(fromAddress, amount, currency = 'VRSCTEST') {
    try {
        const utxos = await makeRPCCall('getaddressutxos', [{
            addresses: [fromAddress],
            currencynames: true
        }]);
        
        const baseFee = 0.001;
        const inputCount = utxos.length;
        const outputCount = 2;
        
        const estimatedSize = (inputCount * 180) + (outputCount * 34) + 10;
        const feeRate = 1;
        const calculatedFee = (estimatedSize * feeRate) / 100000000;
        
        return Math.max(baseFee, calculatedFee);
    } catch (error) {
        console.error('Error estimating fee:', error);
        throw error;
    }
}

/**
 * Validate a Verus address
 * @param {string} address - Address to validate
 * @returns {boolean} Whether the address is valid
 */
export function validateAddress(address) {
    try {
        // Verus addresses start with 'R'
        if (!address.startsWith('R')) {
            return false;
        }

        // Try to decode the address
        bitcoin.address.fromBase58Check(address);
        return true;
    } catch (error) {
        console.error('Address validation error:', error);
        return false;
    }
}

Javascript array destructuring second value is undefined when calling methods

EDIT:
I figured it out. The last line of the file was empty, so [a, b] was destructuring to ["",undefined].

I’m currently doing part 2 of the first Advent of Code problem this year, and I’m trying to create an array of arrays which contain a set of the integers in the first column at index zero, and an array of the integers in the second column at index one, for each row of the data. I’ve included an example of what the data looks like as a string because I’m reading from a file.

const coordinateListString = "56945   59405n28502   39472";

    let aSetBCoordinateList = coordinateListString
      .split("n")
      .map(str => str.split("   "))
      .map(([a, b]) => [new Set([...a].map(Number)), typeof b]);

    console.log(aSetBCoordinateList[0]);

When I run the above snippet with deno I get

[ Set(4) { 1, 8, 0, 2 }, "string" ]

Edit: I should also note removing the typeof yields the correct value ex. "59405".

As you can see b appears to be a string, but when I do b.split(""), I get

error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'split').map(([a, b]) => [new Set([...a].map(Number)), b.split("")]);
                                               ^
at file:///.../part2.js:6:52
at Array.map (<anonymous>)
at file:///..../part2.js:6:4
at eventLoopTick (ext:core/01_core.js:175:7)

const coordinateListString = "56945   59405n28502   39472";

    let aSetBCoordinateList = coordinateListString
      .split("n")
      .map(str => str.split("   "))
      .map(([a, b]) => [new Set([...a].map(Number)), b.split("")]);

    console.log(aSetBCoordinateList[0]);
    console.log(aSetBCoordinateList[0][1]);
    console.log(typeof aSetBCoordinateList[0][1]);

b walks like a string, why doesn’t it quack like one?

How can OpenLayers create their own maps?

click zoo guide map

For example, this zoo guide map defaults to displaying 1-40 positions. When zoomed in, it can display 1-80 positions, and when zoomed in again, it can display all 160 positions. Of course, more details will also be displayed on the guide map

Can you give me an idea for achieving this effect?

I hope this navigation map can be zoomed in and out like a map, displaying more or less

Image url not coming in response

I’m trying to send imageUrl generated from Replicate API, but the imageUrl is not going in response.I have made a credit-based text-to-image generating application but the url seems to not go in response.

Note:The url is in String

import axios from "axios";
import userModel from "../models/UserModel.js";
import FormData from "form-data";
import Replicate from "replicate";
import { writeFile } from "node:fs/promises";
import fs from 'fs';

const replicate = new Replicate({
  auth: process.env.REPLICATE_API_KEY,
});

export const generateImage = async (req, res) => {


  try {

    const { userId, prompt } = req.body;
    const user = await userModel.findById(userId);
    if (!user || !prompt) {
      return res.json({ success: false, message: 'Missing Details' });
    }

    if (user.creditBalance === 0 || user.creditBalance < 0) {
      return res.json({ success: false, message: 'No Credit Balance', creditBalance: user.creditBalance })
    }

    const resultImage = await replicate.run(
      "nvidia/sana:c6b5d2b7459910fec94432e9e1203c3cdce92d6db20f714f1355747990b52fa6",
      {
        input: {
          width: 1024,
          height: 1024,
          prompt: prompt,
          model_variant: "1600M-1024px",
          guidance_scale: 5,
          negative_prompt: "",
          pag_guidance_scale: 2,
          num_inference_steps: 18
        }
      }
    );
    console.log('output' +resultImage)

    await userModel.findByIdAndUpdate(user._id, { creditBalance: user.creditBalance - 1 })
    res.json({
      success: true, message: "Image generated",
      creditBalance: user.creditBalance - 1, resultImage: resultImage
    })

  } catch (error) {

    console.log(error);
    res.json({ success: false, message: error.message })
  }
}

Service worker race condition between message listener and fetch listener

My service worker has a variable to store a secured hash, and injects it into headers for relevant HTTP requests, server app will then compare with its own to make it a secured login.
The hash is generated dynamically behind (in browser class using c# dotnet in my case).

Previously I always called postmessage on page loaded from browser to update the hash into sw. But encountered an issue that with 5-6 min inactive (without opening devtools), once click the button on page, sw is re-initialised or wake up with empty hash value, thus responding with empty value and failed the validation.
So I added a trigger from sw, but then encountered the race condition between message listener and fetch listener. I need the message listener to update the hash in sw, but fetch listener reposonded at same time. Seems timeout delay is not working.

if (!self.secureHeader) {
    self.secureHeader = 'Empty';
    console.log('Refreshing header');

    // this is my trigger when sw re-init
    postMessage({ type: 'refreshHeader', msg: '' }, '*');

    //// this is a bad attempt which didn't block the listener
    // setTimeout(function() {
    //     console.log('timeout ended');
    // }, 50);
}
self.addEventListener('message', function (event) {
    if (event.data.type == 'setHeader') {
        self.secureHeader = event.data.msg;
        console.log('Header received:'+ self.secureHeader);
    } 
}, false);

self.addEventListener('fetch', function(e) {
    console.log(Responding: ${self.secureHeader});
    e.respondWith(
        fetch(request, {
        headers: getSecureHeaders(request)
    })
    .catch(() => {
        return caches.match(request);
    })
    );
});

From the log, after few minutes waiting and sw expiry,
I can see “Refreshing header” triggered first,
then “Header received” and “Responding…” comes at the same time,
how can I properly chain them? Any advice, thanks.

Unable to login subdomain of django tenant, primary domain and admin log in work

I have a multi tenant app using the library django-tenants. When logging into the core URL with the created superuser, the login page works completely fine. When using the subdomain address to login, the page returns a 500 error when using the correct username and password that exists and the console says Uncaught (in promise) SyntaxError: Unexpected token '<', " <!doctype "... is not valid JSON.

When using an login username that doesn’t exist, the output is 400 Bad Request.

The odd part, is I can access the admin panel of a subdomain, log in completely fine, change the URL to go to a part of the app – and the user is now logged in. After being logged in, I can submit forms completely fine and data is being captured, it is solely the login page on a subdomain that has an error submitting.

I am lost since subsequent data forms submit and go correctly, and there are no invalid tokens (from what I see)

views.py


def dual_login_view(request):
    """Authenticate users with both Django Authentication System
    and Django Rest Framework"""
    if request.method == "POST":
        username = request.POST.get("login")
        password = request.POST.get("password")
        user = authenticate(request, username=username, password=password)
        if user is not None:
            # Login user and create session
            login(request, user)

            # Create or get API token
            token, created = Token.objects.get_or_create(user=user)

            response_data = {"status": "success", "token": token.key}
            return JsonResponse(response_data)
        else:
            return JsonResponse(
                {"status": "error", "message": "Username with the password doesn't exist!"}, status=400
            )

        
    return JsonResponse(
        {"status": "error", "message": "Invalid request method"}, status=405
    )


class CustomLoginView(LoginView):

    def form_invalid(self, form):
        for error in form.errors.values():
            for e in error:
                messages.error(self.request, e)
        return super().form_invalid(form)


class UserLoginAPIView(APIView):

    def post(self, request):
        if not (request.user and request.user.is_authenticated):
            return Response(
                {"error": "User not recognized"}, status=status.HTTP_401_UNAUTHORIZED
            )
        try:
            token, created = Token.objects.get_or_create(user=request.user)
            return Response({"token": f"Token {token.key}"}, status=status.HTTP_200_OK)
        except Exception as e:
            print(e)
            return Response(
                {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
            )


class UserLoginAPIView(APIView):
    def post(self, request):
        """Handle user login and return an authentication token."""
        username = request.data.get("username")
        password = request.data.get("password")

        try:
            user = MSPAuthUser.objects.get(username=username)

            # Verify password
            if not user.check_password(password):
                raise ValueError("Invalid credentials")

            token, created = Token.objects.get_or_create(user=user)
            return Response({"token": f"Token {token.key}"}, status=status.HTTP_200_OK)

        except ObjectDoesNotExist:
            return Response(
                {"error": "Invalid credentials"}, status=status.HTTP_401_UNAUTHORIZED
            )

        except ValueError as e:
            return Response({"error": str(e)}, status=status.HTTP_401_UNAUTHORIZED)

login.js

    <script>
        let form = document.querySelector('form');
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            var formData = new FormData(this);

            form.classList.add('was-validated')
            if (!form.checkValidity()) {
                event.preventDefault()
                event.stopPropagation()
                return;
            }
            
            fetch("{% url 'dual_login' %}", {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken'),
                }
            }).then(response => response.json())
              .then(data => {
                  if (data.status === 'success') {
                      // Store the token (e.g., in local storage or a cookie)
                      localStorage.setItem('token', data.token);
                      // Redirect or update the UI
                       window.location.href = '/';
                  } else {
                    Swal.fire({
                        icon: 'error',
                        title: data.message,
                        showConfirmButton: false,
                        timer: 1500,
                    })
                  }
              });
        });

       
    </script> 

Svelte 5 – Unit test when there is style on the component

Im checking out Svelte 5 and I have this simple component

<script lang="ts">
    let {
        name
    }: {
        name: string;
    } = $props();
</script>

<h1>
    Hello! {name}
</h1>

I made a unit test

import { render, screen } from '@testing-library/svelte';
import { describe, it, expect } from 'vitest';
import '@testing-library/jest-dom';
import Header from '../components/Header.svelte';

describe('Header.svelte', () => {
  it('renders with default name', () => {
    render(Header);
    expect(screen.getByText('Hello!')).toBeInTheDocument();
  });

  it('renders with a custom name', () => {
    render(Header, { props: { name: 'John' } });
    expect(screen.getByText('Hello! John')).toBeInTheDocument();
  });
});

This works fine. But if I update/add a style on Header.svelte like:

<script lang="ts">
    let {
        name
    }: {
        name: string;
    } = $props();
</script>

<h1>
    Hello! {name}
</h1>
<style>
    // I added a style tag here. empty and not empty
</style>

This results to error

TypeError: Error while preprocessing path/to/component/Header.svelte –
Cannot create proxy with a non-object as target or handler

❯ new PartialEnvironment
node_modules/vite/dist/node/chunks/dep-yUJfKD1i.js:16766:19 ❯
preprocessCSS
node_modules/vite/dist/node/chunks/dep-yUJfKD1i.js:48447:23 ❯
node_modules/@sveltejs/vite-plugin-svelte/src/preprocess.js:114:10 ❯
style
node_modules/@sveltejs/vite-plugin-svelte/src/preprocess.js:77:37 ❯
process_single_tag
node_modules/svelte/src/compiler/preprocess/index.js:283:21 ❯
replace_in_code
node_modules/svelte/src/compiler/preprocess/replace_in_code.js:70:23
❯ process_tag
node_modules/svelte/src/compiler/preprocess/index.js:300:26 ❯
Module.preprocess
node_modules/svelte/src/compiler/preprocess/index.js:363:25 ❯
compileSvelte
node_modules/@sveltejs/vite-plugin-svelte/src/utils/compile.js:85:20

React Redux: Login Form Flickers on Page Refresh Despite User Being Authenticated

I’m building a React application using Redux for state management. My app checks if the user is already logged in by fetching authentication data from localStorage and dispatching it to Redux. However, I notice a brief flash of the login form on page refresh, even when the user is authenticated. Here’s my code:

function App() {
    const user = useSelector(({ user }) => user);
    const dispatch = useDispatch();
    const [isLoading, setIsLoading] = useState(true);

    async function getUserFromLocalStorage() {
        setIsLoading(true);
        if (!user) {
            const userAuthString = window.localStorage.getItem("userAuth");
            if (userAuthString !== null) {
                const userAuth = JSON.parse(userAuthString); 
                dispatch(loginUserAuth(userAuth));
            }
        }
        setIsLoading(false);
    }

    useEffect(() => {
        getUserFromLocalStorage();
    }, [dispatch]);

    if (isLoading) {
        return (
            <div className='bg-background w-screen h-screen flex items-center justify-center'>
                <SpinnerCircular />
            </div> 
        );
    }

    if (user === null) {
        return (
            <div className='bg-background w-svw h-svh'>
                <Notification />
                <LoginForm />
            </div> 
        );
    }

    return (
        <div className='bg-background w-screen h-screen flex flex-col'>
            <Notification />
            <Routes>
                <Route path="/" element={<Navbar />}>
                    <Route index element={<Home />} />
                    <Route path="/friends" element={<Friends />} />
                    <Route path="/exercises" element={<Exercises />} />
                    <Route path="/food" element={<Food />} />
                    <Route path="/settings" element={<Settings />} />
                </Route>
            </Routes>
        </div>
    );
}

Problem

I suspect the problem lies in how I am using useEffect. Is there a better way to manage this side-effect, particularly for state updates that rely on asynchronous operations? How can I prevent the flicker of the login form while the useEffect is fetching user data and updating the Redux state? Any suggestions would be greatly appreciated.

Set padding of HTML element based on width of preceding element

I am formatting a Shakespearean script in HTML. Because Shakespeare wrote in meter, it is customary to indent lines that do not begin on the first beat of the meter, like so:

p.indent { padding-left: 100pt; }

<h4>HERMIA</h4>
<p>O me!</p>
<h5>[To Helena]</h5>
<p class="indent">You juggler, you cankerblossom,</p>
<p>You thief of love! What, have you come by night</p>
<p>And stol’n my love’s heart from him?</p>
<h4>HELENA</h4>
<p class="indent">Fine, i’ faith.</p>
<p>Have you no modesty, no maiden shame,</p>
<p>No touch of bashfulness? What, will you tear</p>
<p>Impatient answers from my gentle tongue?</p>
<p>Fie, fie, you counterfeit, you puppet, you!</p>

HERMIA

O me!

[To Helena]

        You juggler, you cankerblossom,
You thief of love! What, have you come by night
And stol’n my love’s heart from him?

HELENA

        Fine, i’ faith.
Have you no modesty, no maiden shame,
No touch of bashfulness? What, will you tear
Impatient answers from my gentle tongue?
Fie, fie, you counterfeit, you puppet, you!

However, rather than indent by a fixed amount, it would be ideal to indent to the width of the prior line. That would produce an appearance closer to this:

HERMIA

O me!

[To Helena]

   You juggler, you cankerblossom,
You thief of love! What, have you come by night
And stol’n my love’s heart from him?

HELENA

                 Fine, i’ faith.
Have you no modesty, no maiden shame,
No touch of bashfulness? What, will you tear
Impatient answers from my gentle tongue?
Fie, fie, you counterfeit, you puppet, you!

In the desired solution, the amount of left-padding of each p.indent element should bes equal to the width of the most recent prior p element (which in general is not the most recent prior element, as h4 or h5 elements may intervene).

I assume I can’t do this in pure CSS, but I’ve been surprised about that before. If not, then simple JS?

Postman test script for matching 2 key values inside of each item

Here is how the response tested looks like:

[
    {
        "label": "Summer '14",
        "url": "/services/data/v31.0",
        "version": "31.0"
    },
    {
        "label": "Winter '15",
        "url": "/services/data/v32.0",
        "version": "32.0"
    },
    {
        "label": "Spring '15",
        "url": "/services/data/v33.0",
        "version": "33.0"
    }
]

Now, I want to test to make sure that each URL key for each item contains a value matching the following value: “/services/data/v” + the version number that comes after it must be exactly the same as the version number given for the same items as the value for the version key.

I’ve actually created a piece of script that is receiving a passed result:

pm.test("URL matches the format and version matches the version key", function () {
    const response = pm.response.json();
    
    response.forEach(item => {
        // Extract version from the URL
        const urlPattern = /^/services/data/v(d{2}.d)$/;
        const match = item.url.match(urlPattern);

        // Verify the URL follows the expected format
        pm.expect(match).to.not.be.null; // Ensure the URL matches the pattern

        // Extract the version from the URL if the pattern matched
        const urlVersion = match ? match[1] : null;

        // Verify the extracted version matches the version key
        pm.expect(urlVersion).to.eql(item.version); 
    });
});

Now, what I would need is actually a confirmation from someone who is experienced in Postman testing, or generally in JavaScript is this script is actually doing what I am expecting it to do, as described above.

Render a list of jsx components in react

I have a list, containing some jsx components like components:

components = [
  <span className="c1 c2" onClick={() => console.log("test")}>...</span>,
  <span className="c1 c2" onClick={() => console.log("test")}>...</span>,
  <span className="c1 c2" onClick={() => console.log("test")}>...</span>,
]

BTW the components, is made with pushing into array:

for(...) {
  components.push(<span ...>...</span>)
}

and i use this list as below:

const MyList = () => {
  return (
    <p>{components}</p>
  )
}

the problem is that, after rendering, items don’t have any onClick (or onclick event handler) function.
although they have class property, and the event is set to function noop() {}.
Browsers inspector shows them like:

// there is no 'onclick' function
<span class="c1 c2">...</span>
...

I appreciate any help.