How to correctly download pdf and docx file in React JS?

I am trying to download docx or pdf file in React JS(depending on server response) when I get the response from the server. Backend is implemented in Python/Flask.

When I try to download the file, it downloads but damaged and corrupted.

React JS

function downloadDocument(downloadLink, downloadType) {
 const documentBlob = new Blob([downloadLink], { type: downloadType });
 const url = window.URL.createObjectURL(documentBlob);
 const anchor = document.createElement('a');
 anchor.href = url;
 anchor.download = document_title;
 document.body.appendChild(anchor);
 anchor.click();
 document.body.removeChild(anchor);
 window.URL.revokeObjectURL(url) ;
}

Backend Python/Flask

@app.route('/download_document_docx/<request_document_id>', methods=['GET'])
@token_required
def download_document_docx(current_user, request_document_id):
    '''
    Docx document preparation code
    '''
    return send_file(docx_file_path, as_attachment=True, mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document")

Ionic react datetime showing hours 2 hours in the past

I am new to Ionic React. I am trying to make a calendar app in which I can add/edit/delete Tasks. I can do all of that, but heres the issue.

When I edit the startDate or endDate the time seems to be 2 hours in the past. So when I create a startDate: 7-4-2024 13:00 and endDate 9-4-2024 23:59 and click edit, the values for startDate 7-4-2024 11:00 and for endDate 9-4-2024 21:59

Anyone have any idea on how to fix this? If anyone knows a better approach to doing this, ANY help is welcome :)!

EventComponentList.tsx:

interface TaskComponentProps {
    task: Task;
    index: number; // Index van de taak
    onDelete: () => void;
}

const TaskComponent: React.FC<TaskComponentProps> = ({task, index, onDelete}) => {
    const [newTask, setNewTask] = useState<Task>({...task}); // State for the new task
    const [editing, setEditing] = useState(false); // New state for editing mode
    const [expandedText, setExpandedText] = useState<string | null>(null); // State for expanded text

    const {
        handleInputChange,
        handleDateChange,
        handleToggleChange,
        handleEditTask,
    } = useTaskForm();

    // useEffect hook to reset newTask when editing mode is turned off
    useEffect(() => {
        if (!editing) {
            setNewTask({...task}); // Reset newTask when editing mode is turned off
        }
    }, [editing, task]);

    const handleEditClick = () => {
        setEditing(true); // Turn on editing mode
    };

    const handleSaveClick = () => {
        handleEditTask(index, newTask); // Save the edited task
        setEditing(false); // Turn off editing mode
    };

    const handleCancelClick = () => {
        setEditing(false); // Turn off editing mode
    };

    const toggleExpand = (textType: string) => {
        setExpandedText(expandedText === textType ? null : textType); // Toggle expanded text
    };

     return (
        <IonCard>
            
                <IonList className={'edit-task-form'}>
                    <IonItem>
                      <IonTextarea
                            label={"Name"}
                            labelPlacement={"floating"}
                            autoGrow={true}
                            name="name"
                            value={newTask.title}
                            onIonChange={(e) => setNewTask({...newTask, title: e.detail.value!})}
                        />
                    </IonItem>

                    {/* rest of the inputs */}

                    <IonItem>
                        <IonLabel>Start Date</IonLabel>
                        <IonDatetimeButton datetime="startDate"></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="startDate"
                                onIonChange={handleDateChange('startDate')}
                                value={newTask.startDate.toISOString()}
                            >
                            </IonDatetime>
                        </IonModal>
                    </IonItem>
                    <IonItem>
                        <IonLabel>End Date</IonLabel>
                        <IonDatetimeButton datetime={"endDate"}></IonDatetimeButton>
                        <IonModal keepContentsMounted={true}>
                            <IonDatetime
                                id="endDate"
                                onIonChange={handleDateChange('endDate')}
                                value={newTask.endDate.toISOString()}
                            >
                            </IonDatetime>
                        </IonModal>
                    </IonItem>

TaskHelper.tsx:

export function useTaskForm() {

    const handleDateChange = (name: string) => (e: CustomEvent<any>) => {
        const value = new Date(e.detail.value);
        setNewTask(prevState => ({
            ...prevState,
            [name]: value
        }));
    };

Task.tsx:

interface Task {
  title: string;
  description: string;
  startDate: Date;
  endDate: Date;
  openTimeSlot: boolean;
  remindMe: boolean;
  priority: number;
  category: number;
  url: string;
  note: string;
}

export default Task;

things I’ve tried:
1.
value={newTask.startDate ? newTask.startDate.toISOString() : undefined}
display-timezone=”UTC”
2.
value={newTask.startDate ? newTask.startDate.toISOString() : undefined} // Convert Date to string
onIonChange={(e) => setNewTask({…newTask, startDate: new Date(e.detail.value!)})}
3.
value={newTask.startDate.getTime() + 2 * 60 * 60 * 1000).toISOString()}

none of the above seem to work when editing a Task :`(

how to get current URl from Iframe

I have a requirement where i call api to extend the session , it’s a redirect Api which goes to IDP and IDP calls the rest api via iframe and then it calls the component where the iframe resides. If there is any error then we are passing queryParam “hasError” while calling component from backend. With in the component I am not able to look for queryParam . Can somebody please provide the guidance here :

this is my html : 
<iframe id='myIframe' hidden="hidden" (load)="onLoadIframe(iframe)" title="iframe-authn"></iframe>

this is my component : 

@Component({
    selector: "sso-authn",
    templateUrl: "./sso-authn.component.html"
})
export class SSOAuthNComponent implements AfterViewInit {
@Input()
public loadIframe: boolean;

constructor( @Inject('Window') private window: Window, private webhookServerConfigManager: WebhookServerConfigManager,private router: Router, private acRoute: ActivatedRoute) { }

    ngAfterViewInit() {
        if (this.loadIframe) {
            this.iframe = document.getElementById('myIframe');
            this.iframe.src= "http://localhost.com:4200/extend?goto=http://localhost.ukg.com:4200/sso-authn&realm=ok&compReq=ok;
        }
    }

    onLoadIframe(iframe: any) {
        **//tried to get url with this approach but it is returning parent window location href.**
        const iframeUrl = window.location.href;
  
        let queryParam = this.acRoute.snapshot.queryParams || {};
        if (iframeUrl && iframeUrl.indexOf("hasError") >= 0) {
            // Display session timeout page
            window.parent?.window?.postMessage({ "extendSession": false },     this.ServerConfigManager.ssoOrigin);
            // terminate session and redirect to error page
            console.log('error from auth',queryParam);
            window.parent?.window?.postMessage({ "extendSession": false, "error": queryParam }, this.ServerConfigManager.ssoOrigin);
             this.loadIframe = false;
        } else if (iframeUrl && iframeUrl.indexOf("hasSSO") >= 0) {
            console.log('success response');
            window.parent?.window?.postMessage({ "extendSession": true }, this.ServerConfigManager.ssoOrigin);
            this.loadIframe = false;
        }
    }
path to my component is :  {
    path:'sso-authn',
    component:SSOAuthNComponent
  }

# I want to access queryParam hasError from below url :
http://localhost.com:4200/sso-authn?hasSSO=true&realm=ok&hasError=QVVUSENPREVfSU5WQUxJRA%3D%3D


Webpack 5 Error after Successful build! ( Uncaught Runtime Error Inpage.js )

I’m using webpack version 5 with:

The console leading me to inpage.js file that I don’t have it in my source I assume it’s webpack thing (I’m newbie) and the code that cause’s error is:

setConnectionUrl() {
                return Nc(this, null, function*() {
                    const {nodes: C} = yield this.bm.emit(Mu.GET_NODE, Ve.solana);
                    this.provider.connection = D1(C[0].url)
                })
            }

The part that giving error cannot read properties of undefined (reading '0') is D1(C[0].url

Console Error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
    at U1.<anonymous> (inpage.js:28930:39845)
    at Generator.next (<anonymous>)
    at ce (inpage.js:28930:37705)

I tried Updating all of the subpackages like loaders, babels, etc. But it was not helpful.
I put my github rep link down here so you can take a look at the source and config file yourself.

Clone: https://github.com/mhmdmsvi24/Front-End-Projects.git

It’s my first project and it’s in early stages and each time I reload this bug appears I can click on the X and the projects works just fine but It’s on my nerve.

I do not have enough reputation to post images please clone the project and check it out!

Split PDF File Using PDF.JS

I’m working on a project where I’m trying to process PDF files using OCR (Optical Character Recognition). I’ve managed to split the PDF into individual pages using PDF.js on the client side, but now I’m stuck on how to upload each page to the backend for OCR processing.

Here’s what I’ve done so far:

Successfully integrated PDF.js into my project to split the PDF into separate pages.
I can access each page as a canvas element and perform some basic processing.
However, I’m struggling with the next steps:

How do I upload each page of the PDF to the backend one by one after splitting it using PDF.js?

Is it possible to use react sigma to visualize graph data from neo4j?

I’m trying to build a web application that loads data from neo4j graph database and visualize it with the ability to control node placement and send query to sort the graph in different ways. I’ve heard of neosigma library that connects neo4j database to sigma js for visualization, but i don’t know if it’s possible to use it with react-sigma, especially since i’m still learning react and javascript along with it.

The farthest i’ve gone is trying react-sigma basic and neosigma library. the former is successful but since it use the example dataset made from randomly generated names, i’m not sure on how it works with a database and the limitations, and the latter i’m not even sure where to start.

MedusaJS does not trigger subscribers. Why?

I wrote a subscriber to send messages when placing an order, but it is not triggered. I removed all the code from my email client and left only the logs, but it still doesn’t work.
event-bus-redis works, new events are created in my redis.

import {
    Logger,
    OrderService,
    SubscriberArgs,
    SubscriberConfig,
} from "@medusajs/medusa";

type OrderPlacedEvent = {
    id: string;
    no_notification: boolean;
};

export default async function orderPlacedHandler({data, eventName, container}: SubscriberArgs<OrderPlacedEvent>) {

    const logger = container.resolve<Logger>("logger")

    console.log("Order placed event received")
    console.log(data)
    console.log(eventName)

    logger.log("Order placed event received")


    const orderService: OrderService = container.resolve('orderService');

    const order = await orderService.retrieve(data.id, {
        relations: ["items", "items.variant", "items.variant.product"],
    });

    // Do something with the order
}

export const config: SubscriberConfig = {
    event: OrderService.Events.PLACED,
    context: {
        subscriberId: "order-place-handler",
    },

};

Issue with Preventing Form Submission in JavaScript

Title: Issue Preventing Form Submission when Uploading Files in JavaScript

I’m facing an issue with preventing form submission in my JavaScript code. I have a form that allows users to input messages and optionally upload files or images. The objective is to prevent the form from submitting when a file is being uploaded to avoid reloading the page and losing the chat history.

Here’s the relevant JavaScript code:

const form = document.getElementById('send-container');

// Event listener for form submission
form.addEventListener('submit', (e) => {
    e.preventDefault();
    // Check if a message is being sent
    if (messageInput.value.trim() !== '') {
        const message = messageInput.value;
        append(`You: ${message}`, 'right');
        socket.emit('send', message);
        messageInput.value = '';
    }
});

// Event listener for form submission
form.addEventListener('submit', (e) => {
    // Check if a file is being uploaded
    if (myfileInput.files.length > 0) {
        const file = myfileInput.files[0];
        const reader = new FileReader();

        reader.onload = function(event) {
            const base64Data = event.target.result;
            socket.emit('image', { name: file.name, data: base64Data });
            append(`You: ${file.name}`, 'right');
            myfileInput.value = '';
        };

        reader.onerror = function(event) {
            console.error('Error reading file:', event.target.error);
        };

        reader.readAsDataURL(file);
    }
    e.preventDefault();
});

To prevent form submission when files or images are being uploaded

Javascript does not execute if a link opens new web page [closed]

Javascript executes only when I refresh page on a browser, but it does not execute when the page renders first time after following a link.
I use Symfony 7 on Mysql database.

<a class="btn btn-success rounded-pill" href="{{ path('fill_and_sign_contract', {'id': contract.getId()}) }}">Sign</a>

After pressing the link page loads very quickly, but javascript does not executes.
I am working locally on my dev environment and I use Symfony debug toolbar.

Is there any function by that directly convert array in below format [closed]

array =[
    "Ayush",
    "85685698",
    "[email protected]",
    "jaipur",
    "SE",
    "PS",
    "Rishabh",
    "69856985",
    "[email protected]",
    "gujrat",
    "SSE",
    "Dev"
];

How to convert above array in below format

array =[
  {name:"Ayush",contact:"85685698",email:"[email protected]",city:"jaipur",role:"SE",org:"PS"},
  {name:"Rishabh",contact:"69856985",email:"[email protected]",city:"gujrat",role:"SSE",org:"Dev"}
]

Addeventlistener working on web but not on mobile

I have a search input element and a button on shopify’s header.
We are attaching click and touchend event listeners on the button. So that our function executes in both web and mobile. Until now we were working with enter button to be clicked but now we want the search to work with click of searchIcon as well.
The problem is, our function executes for web but not on mobile. (Not even on responsive mobile mode in a desktop browser)

Later I also tried attaching the events on the button inside the focus event handler of the input element
Here is the excerpt:

 const onFocus = () => {
      const searchIcon = document.querySelector(".site-header__search-btn--submit") as HTMLButtonElement;
      if (myStore) {

        ["click", "touchend"].forEach((event) => {
          searchIcon.addEventListener(
            event,
            (e) => {
              e.preventDefault();
              console.log("searchIcon.previousElementSibling", searchIcon.previousElementSibling);
              handleEnterPress(searchIcon.previousElementSibling as HTMLInputElement);
            },
            true
          );
        }); // Adding event listener to search Icon
      }
    };

    searchInput.addEventListener("keydown", onInputKeyDown);
    searchInput.addEventListener("input", debounceSearch, false);

    onFocus();
    searchInput.addEventListener("focus", onFocus);

Note that the events are added inside the useEffect of my own overlay component with empty dependencies.

Also on printing the SearchIcon on console and on hovering on it from console, the SearchIcon does not get highlighted in mobile but it gets highlighted on web.

how to clean my typescript type and make it’s code simple?

I have an interface in my code which contains some fields and i’m creating some types based on it’s fields dynamically.

consider the interface like below

interface Fields<T> {
    type1_field1?: T;
    type1_field2?: T;
    type1_field3?: T;
    type2_field1?: T;
    type2_field2?: T;
    type3_field1?: T;
    type3_field2?: T;
    type3_field3?: T;
    type4_field1?: T;
}

and these interfaces are created based its fields.(i have types in my code but here just wanna explain my code so i use interfaces)

interface Type1<T> {
    type1_field1: T;
    type1_field2: T;
    type1_field3: T;
}

interface Type2<T> {
    type2_field1: T;
    type2_field2: T;
}

interface Type3<T> {
    type3_field1: T;
    type3_field2: T;
    type3_field3: T;
}

interface Type4<T> {
    type4_field1: T;
}

i want to create some types that are creating map between Type1, Type2, Type3, Type4.
consider below example:

type ValidateField<T> = T & { [i in keyof Omit<Fields<T>, keyof T>]?: never };

type Result1<T> = ValidateField<Type1<T> & Type3<T>> | ValidateField<Type1<T> & Type4<T>> | ValidateField<Type1<T> & Type2<T>>;
// in all ValidationFiels usage for result1 the first part of mapping always is Type1
type Result2<T> = ValidateField<Type2<T> & Type3<T>> | ValidateField<Type2<T> & Type4<T>>;
// in all ValidationFiels usage for result2 the first part of mapping always is Type2

so for example in Result2 type i want this result:

type Result2<T> = {
    type1_field1?: never;
    type1_field2?: never;
    type1_field3?: never;
    type2_field1?: T;
    type2_field2?: T;
    type3_field1?: T;
    type3_field2?: T;
    type3_field3?: T;
    type4_field1?: never;
} | {
     type1_field1?: never;
    type1_field2?: never;
    type1_field3?: never;
    type2_field1?: T;
    type2_field2?: T;
    type3_field1?: never;
    type3_field2?: never;
    type3_field3?: never;
    type4_field1?: T;
}

i want to choose only some fields and the others should be never type.

my code is working fine but the problem is i have to repeat

ValidateField<Type1<T> & Type3<T>> | ValidateField<Type1<T> & Type4<T>>
pattern so many times. maybe i can use some other validator type to make these type definitions simple.
for example to create Result1 something that take Type1 and Type2 | Type3 | Type4 and map Type1 with those 3 other types.
do you have any idea that might help clean this code?

Correct Setup WordPress for refreshing API data on server until

I am a bit stuck with my thoughts on a wordpress project.

Outline:

  1. On page load an API call to endpoint1 should be made (I use the plugin WPgetAPI for this matter, it works for getting POST data for me)
  2. From the response I expect a QR image and a OrderRef (done)
  3. QRCode needs to be prompted on page, user should scan
  4. With OrderRef from endpoint1, endpoint2 is called for status updates. The OrderRef must be the same string as from the first endpoint call
  5. Endpoint responses pending until the QR code is scanned or timed
  6. When status is switching to complete in the API endpoint response the javascript loop should stop and it should be prompted a success message on the page
  7. I start the page load and the functions for calling the API are currently placed in my themes functions.php, once page load is done, call 1 is facilitated, js calls the ajax refreshing.
  8. The javascript is separated file called my-script.js

My problem:

For versatility, I want to use this on different spaces on my page, I insert this with WPCode Shortcode into the page. That works!

On page load the api returns correctly a OrderRef and I can prompt QR code. That works!

The logs in browser console indicates that in the Javascript and php page where different orderRefs used, I could contain the problem, but I am not really coming there that the javascript. The logs now indicate same orderRef is used:

[Log] JQMIGRATE: Migrate is installed with logging active, version 3.4.1 (jquery-migrate.js, line 104)
[Log] OrderRef set for AJAX: – "e1e012f1-6b6d-44d8-9473-1d164b151230" (test-wp-api-stage, line 1250)
[Log] OrderRef in the Javascript file: – "e1e012f1-6b6d-44d8-9473-1d164b151230" (my-script.js, line 2)
[Log] Sending AJAX request with data: – {action: "check_status", OrderRef: "e1e012f1-6b6d-44d8-9473-1d164b151230"} (my-script.js, line 5)
[Log] AJAX call successful. Response: – "" (my-script.js, line 15)

I do not really come to success building the loop so that WordPress manages to facilitate the refreshing of the status in endpoint2 function (), updates the page with response status and then ends the javascript once the status is completed.

My excerpt from the functions.php where I enqueue the scripts and set the functions for calling the endpoints.

function prepare_global_api_data() {
    global $globalApiData;
    if (!did_action('wp')) {
        return;  
    }
    $response = wpgetapi_endpoint('bank_id', 'endpoint1');
    if ($response && isset($response['apiCallResponse']['Response'])) {
        $globalApiData = [
            'OrderRef' => $response['apiCallResponse']['Response']['OrderRef'],
            'QrImage' => $response['apiCallResponse']['Response']['QrImage']
        ];
    } else {
        $globalApiData = ['OrderRef' => 'default-value', 'QrImage' => ''];
    }
    error_log('API Data prepared: ' . print_r($globalApiData, true));
}
add_action('wp', 'prepare_global_api_data'); 

// Localize script after making sure it's enqueued
function generate_and_enqueue_scripts() {
    global $globalApiData;
    wp_enqueue_script('jquery');
    wp_enqueue_script('my-script', get_template_directory_uri() . '/scripts/my-script.js', array('jquery'), '1.0.0', true);
    
    wp_localize_script('my-script', 'my_script_vars', [
        'OrderRef' => $globalApiData['OrderRef'],
        'ajax_url' => admin_url('admin-ajax.php')
    ]);
}
add_action('wp_enqueue_scripts', 'generate_and_enqueue_scripts');

// AJAX callback 
function check_status_callback() {
    if (empty($_POST['OrderRef'])) {
        echo 'Error: OrderRef is missing.';
        wp_die();
    }
    $OrderRef = sanitize_text_field($_POST['OrderRef']);
    $fields = ['OrderRef' => $OrderRef];
    $response2 = wpgetapi_endpoint('bank_id', 'endpoint2', ['body_variables' => $fields]);

    wp_die();
}
add_action('wp_ajax_check_status', 'check_status_callback');
add_action('wp_ajax_nopriv_check_status', 'check_status_callback');

The code snippet on my page.php

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$response = wpgetapi_endpoint('bank_id', 'endpoint1'); // First API call
if (is_array($response) && !empty($response['authResponse']) &&  is_array( $response['authResponse']['Success'])) {
    if (!empty($response['apiCallResponse']) && $response['apiCallResponse']['Success']) {
        $OrderRef = $response['apiCallResponse']['Response']['OrderRef']; // Store OrderRef in variable
        $autoStartToken = $response['apiCallResponse']['Response']['AutoStartToken']; // Capture AutoStart Token
        $qrImage = $response['apiCallResponse']['Response']['QrImage']; // Capture QR Image URL
        error_log('OrderRef set from endpoint1: ' . $OrderRef);
    }
}

// Ensure all variables are defined even if not set initially
$autoStartToken = $response['apiCallResponse']['Response']['AutoStartToken'] ?? 'Not Available';
$qrImage = $response['apiCallResponse']['Response']['QrImage'] ?? '';
?>

<style>
    .api-response {
        text-align: center;
    }
    .static-block, .dynamic-status {
        border: 1px solid #ccc;
        padding: 10px;
        margin-top: 20px;
        text-align: left;
    }
</style>

<div class="api-response">
    <div id="qrCodeContainer">
        <?php if (isset($OrderRef)): ?>
            Authentication successful. <br>
            Order Reference: <?php echo esc_html($OrderRef); ?><br>
            AutoStart Token: <?php echo esc_html($autoStartToken); ?><br>
            <img src="<?php echo esc_url($qrImage); ?>" alt="QR Code" id="qrCode"><br>
        <?php else: ?>
            Failed to authenticate or retrieve the Order Reference.
        <?php endif; ?>
    </div>

    <!-- Dynamic content area for AJAX updates -->
    <div id="statusMessageContainer" class="dynamic-status">
        Please scan the QR code. Status updates will appear here after scanning.
    </div>
</div>

<script type="text/javascript">
    // Immediately output the OrderRef into JavaScript context
    var my_script_vars = {
        OrderRef: '<?php echo $OrderRef ?? ''; ?>',
        ajax_url: '<?php echo admin_url('admin-ajax.php'); ?>'
    };
    console.log("OrderRef set for AJAX in PHP file:", my_script_vars.OrderRef); // Log this to console for debugging
</script>

The javascript .js
jQuery(document).ready(function($) {
    function checkStatus() {
        console.log('Making AJAX call with OrderRef:', my_script_vars.OrderRef);

        $.ajax({
            url: my_script_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'check_status',
                OrderRef: my_script_vars.OrderRef
            },
            success: function(response) {
                console.log('AJAX call successful. Response:', response);
                // Update only the status message container
                $('#statusMessageContainer').html(response);
            },
            error: function(xhr, status, error) {
                console.error('AJAX call failed. Error:', error);
                $('#statusMessageContainer').html('<p>Error fetching data. Please try again.</p>');
            }
        });
    }

    // Set an interval to call checkStatus every 5 seconds (5000 milliseconds)
    setInterval(checkStatus, 5000);
});

Could you help me finding the problem with me how I get these 3 parts together so I can make a working process why the response from the endpoint2 call is not correctly showing.

The log [Log] AJAX call successful. Response: – “” (my-script.js, line 13) indicates that the javascript has no OrderRef, but I really don’t understand why.

Thanks

Tried several debugging approaches and logged the files, restructered the code, but I can’t find the error of the missing OrderRef

Puppeteer library error, although i am not even using it

I was earlier using library puppeteer to make a pdf from html and send it on email, but it is taking so much time, so i moved to another library, but no matter how it is giving me error of ====>
Error: Failed to launch the browser process!
1|app | ‘/var/node_backend/node_modules/html-pdf-node/node_modules/puppeteer/.local-chromium/linux-901912/chrome-linux/chrome: error while loading shared libraries: libatk-1.0.so.0: cannot open shared object file: No such file or directory’
although it is working fine on local, but on gcp intance it is giving me this error. i am using ubuntu machine for gcp.

let options = { format: 'A4' }; let file = { content: html_content }; html_to_pdf.generatePdf(file, options).then(pdfBuffer => { // Your code to handle the PDF buffer goes here });
This is the code which i am using to do it. Help me to fix this

How to import fbx file into java spring boot application properly using three.js

Hi I am trying to make spring java application which simply get simple cube mesh fbx and render by three.js. I have read offical three.js documentation and searched stackoverflow but got nothing

the below is part of html code for upload fbx filet

<form action="/isearch" data-transition="fade" enctype="multipart/form-data">
<input type="file" name="file" accept=".fbx" required/>
<buttontype="submit"></button>
</form>

and below is the part of controller code for /isearch mapping

@PostMapping("/isearch")
    public String uploadModel(Model model, @PageableDefault(size = 6) Pageable pageable,
                              @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            logger.warn("Upload attempt with empty file");
            return "redirect:/uploadError";
        }

        String directoryPath = "src/main/resources/static/3dmodels/";
        String originalFileName = file.getOriginalFilename();
        Path path = Paths.get(directoryPath + File.separator + originalFileName);

        try (InputStream inputStream = file.getInputStream(); Reader reader = new InputStreamReader(inputStream)) {
            if (!Files.exists(path)) {
                Files.copy(inputStream, path);
            }

            String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
                .replacePath(null)
                .build()
                .toUriString();

            String fileUrl = baseUrl + "/3dmodels/" + originalFileName;
            model.addAttribute("fileUrl", fileUrl);

            logger.info("File successfully uploaded and accessible at: {}", fileUrl);

        } catch (IOException e) {
            e.printStackTrace();
            logger.error("Error occurred while uploading file", e);
            return "redirect:/uploadError";
        }
        return "isearch.jsp";
    }

and the below is the html file code with js code for rendering cube

<div id="canvas" background-color: transparent;">

            </div>
            
<script>
    var modelPath = "${fileUrl}";
    type="module" src="${pageContext.request.contextPath}/resources/js/3drender.js">
</script>           
    import * as THREE from 'https://unpkg.com/three/build/three.module.js';
    import { FBXLoader } from 'https://unpkg.com/three/examples/jsm/loaders/FBXLoader.js';

    let scene, camera, renderer, clock, mixer;

    function init() {
        const container = document.getElementById('model-container');

        scene = new THREE.Scene();

        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.set(0, 100, 200);
        camera.lookAt(scene.position);

        renderer = new THREE.WebGLRenderer({ alpha: true });
        renderer.setClearColor(0x000000, 0);
        renderer.setSize(container.clientWidth, container.clientHeight);
        container.appendChild(renderer.domElement);

        const ambientLight = new THREE.AmbientLight(0x404040, 2);
        scene.add(ambientLight);
        const directionalLight = new THREE.DirectionalLight(0xffffff, 3);
        directionalLight.position.set(0, 10, 10);
        scene.add(directionalLight);

        const loader = new THREE.FBXLoader();
        loader.load('${imagePath}', function (object) {
            mixer = new THREE.AnimationMixer(object);
            const action = mixer.clipAction(object.animations[0]);
            action.play();

            object.traverse(function (child) {
                if (child.isMesh) {
                    child.material = new THREE.MeshStandardMaterial({color: 0xff0000});
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
            });
            object.scale.set(0.1, 0.1, 0.1);
            scene.add(object);
            animate();
        });

        function animate() {
            requestAnimationFrame(animate);
            const delta = clock.getDelta();
            if (mixer) mixer.update(delta);
            renderer.render(scene, camera);
        }

        clock = new THREE.Clock();
    }

    window.onload = init;

it shows html rendering page but I cannot see nothing

I want to render simple cube mesh in website by uploading simplecube.fbx

but there are few materials for references

If there exist any tutorial for this please give me a hint please

thank you