Horizontal paging in the WebView is not working perfectly on Xiaomi devices

The ePub reader utilizes a WebView and JavaScript for horizontal book reading, but the pages are not divided perfectly on Xiaomi devices. Other devices are functioning correctly. Here is the reference indicating the issue we’re encountering on Xiaomi devices with the WebView, using the below JavaScript function.(Issue)

function initHorizontalDirection(deviceName) {

    preInitHorizontalDirection();
    postInitHorizontalDirection(deviceName);

}

function preInitHorizontalDirection() {

    //console.log(window);
    //console.log("-> " + document.getElementsByTagName('title')[0].innerText);
    var htmlElement = document.getElementsByTagName('html')[0];
    var bodyElement = document.getElementsByTagName('body')[0];

    // Required when initHorizontalDirection() is called multiple times.
    // Currently it is called only once per page.
    htmlElement.style.width = null;
    bodyElement.style.width = null;
    htmlElement.style.height = null;
    bodyElement.style.height = null;

    var bodyStyle = bodyElement.currentStyle || window.getComputedStyle(bodyElement);
    var paddingTop = parseInt(bodyStyle.paddingTop, 10);
    var paddingRight = parseInt(bodyStyle.paddingRight, 10);
    var paddingBottom = parseInt(bodyStyle.paddingBottom, 10);
    var paddingLeft = parseInt(bodyStyle.paddingLeft, 10);
    //console.log("-> padding = " + paddingTop + ", " + paddingRight + ", " + paddingBottom + ", " + paddingLeft);

    //document.documentElement.clientWidth is window.innerWidth excluding x scrollbar width
    var pageWidth = document.documentElement.clientWidth - (paddingLeft + paddingRight);
    //document.documentElement.clientHeight is window.innerHeight excluding y scrollbar height
    var pageHeight = document.documentElement.clientHeight - (paddingTop + paddingBottom);

    bodyElement.style.webkitColumnGap = (paddingLeft + paddingRight) + 'px';
    bodyElement.style.webkitColumnWidth = pageWidth + 'px';
    bodyElement.style.columnFill = 'auto';

    htmlElement.style.height = (pageHeight + (paddingTop + paddingBottom)) + 'px';
    bodyElement.style.height = pageHeight + 'px';
}

function postInitHorizontalDirection(deviceName) {

    var htmlElement = document.getElementsByTagName('html')[0];
    var bodyElement = document.getElementsByTagName('body')[0];
    var bodyStyle = bodyElement.currentStyle || window.getComputedStyle(bodyElement);
    var paddingTop = parseInt(bodyStyle.paddingTop, 10);
    var paddingRight = parseInt(bodyStyle.paddingRight, 10);
    var paddingBottom = parseInt(bodyStyle.paddingBottom, 10);
    var paddingLeft = parseInt(bodyStyle.paddingLeft, 10);
    var clientWidth = document.documentElement.clientWidth;

    var scrollWidth = document.documentElement.scrollWidth;
    if (scrollWidth > clientWidth
        && scrollWidth > document.documentElement.offsetWidth) {
//        if (deviceName.toString().toLowerCase().includes("poco") || deviceName.toString().toLowerCase().includes("xiaomi")) {
//            scrollWidth -= paddingRight;
//        } else {
            scrollWidth += paddingRight;
//        }
    }
    var newBodyWidth = scrollWidth - (paddingLeft + paddingRight);
    window.scrollWidth = scrollWidth;

    htmlElement.style.width = scrollWidth + 'px';
    bodyElement.style.width = newBodyWidth + 'px';

    // pageCount deliberately rounded instead of ceiling to avoid any unexpected error
    var pageCount = Math.round(scrollWidth / clientWidth);
    var pageCountFloat = scrollWidth / clientWidth;

    if (pageCount != pageCountFloat) {
        console.warn("-> pageCount = " + pageCount + ", pageCountFloat = " + pageCountFloat
            + ", Something wrong in pageCount calculation");
    }

    FolioPageFragment.setInitHorizontalDirectionSuccessfully(pageCount);
}

ExpecingLike This

Why nodemailer smtp don’t access my account?

I made a mail service and wanted to use smtp for mailing, but when I try to log in, the login or password is not accepted, although they are 100 percent entered correctly. What should I do?

import nodemailer from "nodemailer";
import { config } from "dotenv";
config({ path: "./other/.env" });

const SMTP_HOST = process.env.SMTP_HOST || "smtp.gmail.com";
const SMTP_PORT = process.env.SMTP_PORT || 587;
const SMTP_USER = process.env.SMTP_USER || "smpt user is not working";
const SMTP_PASSWORD = process.env.SMTP_PASSWORD || "smtp password is not working";
const SITE_URL = process.env.SITE_URL || "site url is not working";

class MailService {
    transporter;

    constructor() {
        this.transporter = nodemailer.createTransport({
            host: SMTP_HOST,
            port: SMTP_PORT,
            secure: false,
            auth: {
                user: SMTP_USER,
                pass: SMTP_PASSWORD
            }
        } as nodemailer.TransportOptions);
    }

    async sendActivationMail(to: string, link: string) {
        await this.transporter.sendMail({
            from: SMTP_USER,
            to,
            subject: "Account's activation on " + SITE_URL,
            text: '',
            html:
                `
                    <div>
                        <h1>For actovation click on this link</h1>
                        <a href="${link}">${link}</a>
                    </div>
                `
        })
    }
}

export default new MailService();
Error: Invalid login: 535-5.7.8 Username and Password not accepted. For more information, go to535 5.7.8  https://support.google.com/mail/?p=BadCredentials x28-20020a056512131c00b0051979e3a586sm1546821lfu.266 - gsmtpat SMTPConnection._formatErrorat SMTPConnection._actionAUTHCompleteat SMTPConnection.<anonymous>at SMTPConnection._processResponseat SMTPConnection._onDataat SMTPConnection._onSocketDataat TLSSocket.emit (node:events:513:28)at addChunk (node:internal/streams/readable:324:12)at readableAddChunk (node:internal/streams/readable:297:9)at Readable.push (node:internal/streams/readable:234:10) {code: 'EAUTH',response: '535-5.7.8 Username and Password not accepted. For more information, go ton' +'535 5.7.8  https://support.google.com/mail/?p=BadCredentials x28-20020a056512131c00b0051979e3a586sm1546821lfu.266 - gsmtp',responseCode: 535,command: 'AUTH PLAIN

I tried all ai chats, not helped.

zoom in not working only able to zoom out works but in console the zoom values are correct but not visible on screen

Zoom is not working only zoom out is working i wanted the canvas to fit the viewport maybe something related to that not sure

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Cropper</title>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
    <style>
        body,
        html {
            height: 100%;
            margin: 0;
            padding: 0;
            background: black;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        .controls {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            pointer-events: none;
            /* Allows clicks to pass through */
        }

        .controls button,
        .controls select {
            pointer-events: auto;
            /* Re-enable pointer events for controls */
            background-color: black; /* Set button background to black */
            color: white; /* Set text color to white */
        }

        .top-right {
            position: absolute;
            top: 10px;
            right: 10px;
        }

        .top-left {
            position: absolute;
            top: 10px;
            left: 10px;
        }

        .bottom-left {
            position: absolute;
            bottom: 10px;
            left: 10px;
        }

        .bottom-right {
            position: absolute;
            bottom: 10px;
            right: 10px;
        }

        .image-container-wrapper {
            /* width: 80%; */
            /* height: 80%; */
            max-width: 90vw;
            max-height: 90vh;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: visible;
            /* Important to make sure that anything beyond the bounds is hidden */
        }

        .image-container {
            position: relative;
            width: 100%;
            height: 100%;
        }

        canvas {
            width: 100%;
            /* Might restrict enlargement depending on parent's fixed dimensions */
            height: 100%;
            display: block;
        }

        .overlay {
            position: absolute;
            border: 2px solid yellow;
            cursor: move;
            touch-action: none;
            z-index: 1;
        }

        .corner {
            position: absolute;
            width: 15px;
            height: 15px;
            background-color: yellow;
            border-radius: 50%;
        }

        .corner.top-left {
            top: -7.5px;
            left: -7.5px;
        }

        .corner.top-right {
            top: -7.5px;
            right: -7.5px;
        }

        .corner.bottom-left {
            bottom: -7.5px;
            left: -7.5px;
        }

        .corner.bottom-right {
            bottom: -7.5px;
            right: -7.5px;
        }

        .overlay-background {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            pointer-events: none;
        }
    </style> </head>

<body>
    <div class="controls">
        <select id="shapeSelect" onchange="selectShape()" class="top-left">
            <option value="rectangle" selected>Rectangle</option>
            <option value="circle">Circle</option>
        </select>
        <button id="cropButton" class="top-right">Crop</button>
        <div class="bottom-left">
            <button onclick="rotateImage(-90)"><i class="fas fa-undo"></i></button>
            <button onclick="rotateImage(90)"><i class="fas fa-redo"></i></button>
        </div>
        <div class="bottom-right">
            <button onclick="zoomImage(1.2)"><i class="fas fa-search-plus"></i></button>
            <button onclick="zoomImage(0.8)"><i class="fas fa-search-minus"></i></button>
        </div>
    </div>
    <div class="image-container-wrapper">
        <div class="image-container">
            <div class="overlay-background"></div>
            <canvas id="canvas"></canvas>
            <div class="overlay">
                <div class="corner top-left"></div>
                <div class="corner top-right"></div>
                <div class="corner bottom-left"></div>
                <div class="corner bottom-right"></div>
            </div>
        </div>
    </div>
    <!-- <div id="croppedImagePreview"></div> -->

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const canvas = document.getElementById("canvas");
            const ctx = canvas.getContext("2d");
            const imageObj = new Image();
            const overlay = document.querySelector('.overlay');
            const overlayBackground = document.querySelector('.overlay-background');
            let selectedShape = "rectangle";
            let angle = 0;
            let zoomFactor = 1;  // Initial zoom factor

            imageObj.onload = function () {
                drawRotatedImage();
            };

            imageObj.crossOrigin = "Anonymous";
            imageObj.src = 'rope41.png'; // Update image URL

            window.selectShape = function () {
                selectedShape = document.getElementById("shapeSelect").value;
                overlay.style.borderRadius = selectedShape === "circle" ? "50%" : "0%";
            };

            window.rotateImage = function (deg) {
                angle = (angle + deg) % 360;
                drawRotatedImage();
                // This should be done after redrawing the image and possibly resizing the overlay.
                setTimeout(function () {
                    initializeOverlay();
                }, 100); // Delay might be needed for the DOM updates to settle
            }

            window.zoomImage = function (factor) {
                zoomFactor *= factor;
                console.log("Zoom Factor: " + zoomFactor);
                drawRotatedImage();
            }

            function drawRotatedImage() {
                const radians = angle * Math.PI / 180;
                const sin = Math.abs(Math.sin(radians));
                const cos = Math.abs(Math.cos(radians));

                const imageWidth = cos * imageObj.width + sin * imageObj.height;
                const imageHeight = sin * imageObj.width + cos * imageObj.height;

                const scaleX = (window.innerWidth / imageWidth) * zoomFactor;
                const scaleY = (window.innerHeight / imageHeight) * zoomFactor;
                const scaleToFit = Math.min(scaleX, scaleY);

                console.log("Canvas dimensions: " + canvas.width + " x " + canvas.height);

                const canvasWidth = imageWidth * scaleToFit;
                const canvasHeight = imageHeight * scaleToFit;

                canvas.width = canvasWidth;
                canvas.height = canvasHeight;

                ctx.setTransform(scaleToFit, 0, 0, scaleToFit, canvasWidth / 2, canvasHeight / 2);
                ctx.rotate(radians);
                ctx.drawImage(imageObj, -imageObj.width / 2, -imageObj.height / 2);

                ctx.setTransform(1, 0, 0, 1, 0, 0);

                initializeOverlay();
            }


            function initializeOverlay() {
                const containerRect = document.querySelector('.image-container-wrapper').getBoundingClientRect();
                overlay.style.width = `${containerRect.width - 4}px`;
                overlay.style.height = `${containerRect.height - 4}px`;
                overlay.style.top = '0px';
                overlay.style.left = '0px';

                setupOverlayInteractions(containerRect.width - 4, containerRect.height - 4);
            }

            function setupOverlayInteractions(width, height) {
                if ($.data(overlay, 'ui-resizable')) {
                    $(overlay).resizable('destroy');
                }
                if ($.data(overlay, 'ui-draggable')) {
                    $(overlay).draggable('destroy');
                }

                // Set up resizable
                $(overlay).resizable({
                    containment: "parent",
                    handles: 'n, e, s, w, ne, se, sw, nw',
                    minWidth: 50,
                    minHeight: 50,
                    resize: function (event, ui) {
                        updateOverlayBackground(ui.position, ui.size);
                    }
                });

                // Set up draggable
                $(overlay).draggable({
                    containment: "parent",
                    drag: function (event, ui) {
                        updateOverlayBackground(ui.position, { width: ui.helper.width(), height: ui.helper.height() });
                    }
                });

                updateOverlayBackground({ top: '0px', left: '0px' }, { width, height });
            }

            function updateOverlayBackground(position, size) {
                const left = parseFloat(position.left) || 0;
                const top = parseFloat(position.top) || 0;
                const width = parseFloat(size.width) || 0;
                const height = parseFloat(size.height) || 0;

                overlayBackground.style.clipPath = `polygon(
                    0 0, 
                    0 100%, 
                    ${left}px 100%, 
                    ${left}px ${top}px, 
                    ${left + width}px ${top}px, 
                    ${left + width}px ${top + height}px, 
                    ${left}px ${top + height}px, 
                    ${left}px 100%, 
                    100% 100%, 
                    100% 0
                )`;
            }

            document.getElementById('cropButton').addEventListener('click', function () {
                const canvasRect = canvas.getBoundingClientRect();
                const bounds = overlay.getBoundingClientRect();

                const scaleX = canvas.width / canvasRect.width;
                const scaleY = canvas.height / canvasRect.height;

                const cropX = (bounds.left - canvasRect.left) * scaleX;
                const cropY = (bounds.top - canvasRect.top) * scaleY;
                const cropWidth = bounds.width * scaleX;
                const cropHeight = bounds.height * scaleY;

                const croppedCanvas = document.createElement("canvas");
                const croppedCtx = croppedCanvas.getContext("2d");
                croppedCanvas.width = cropWidth;
                croppedCanvas.height = cropHeight;

                croppedCtx.drawImage(canvas, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);

                // const imgPreview = document.getElementById('croppedImagePreview');
                // imgPreview.innerHTML = '';
                const img = new Image();
                img.src = croppedCanvas.toDataURL("image/png");
                console.log("Base64", img.src);
                // imgPreview.appendChild(img);
            });
        });
    </script> </body>

</html>

how to create sppining list in html/css/js like tide.com

my question is how to make a rotating spinner list like tide.com stains list design in HTML5

i saw this solution How to make a HTML5 spinning list/rotating wheel selector/picker but i want something with more dynamic design for faded text for top and bottom list and updating link

something like this image:
tide.com spinning list

simple and easy to change design with top and bottom faded with mouse scroll and drag-able with touch

“error”: “415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not ‘application/json’.”

I am working on a React-Python(Flask) project. I keep getting the error ‘415 Unsupported Media Type: Did not attempt to load JSON data because the request Content-Type was not ‘application/json’. I don’t know whether the issue is with backend side or the frontend.
I have rechecked my React endpoint and I don’t see where the problem could be:

export const StudentRegister = () => {
  const [form] = Form.useForm();

  const onFinish = async (values: any) => {
    try {
      const formData = new FormData()
      
      if (values.image && values.image.length > 0) {
        formData.append('image', values.image[0].originFileObj);
        console.log(formData)
      }  
      
      const imageResponse = await fetch('/facial-data', {
        method: 'POST',
        body: formData
      })

      const imageResult = await imageResponse.json();
      console.log('Image upload response:', imageResult);

      delete values.image;

      const formResponse = await fetch('http://localhost:5000/student', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(values),
      });

      const data = await formResponse.json();

      if (formResponse.ok) {
        message.success(data.message);
        form.resetFields();
        
      } else {
        message.error(data.error);
      }
    } catch (error) {
      console.error('Error:', error);
    }

    window.location.href = '/login';
  };

  return ()

And my flask endpoint also looks okay to:

@app.route('/student', methods=['GET','POST'])
def register():
    print(request.headers)
    print("---------")
    print(request.data)
    session = Session()

    try:
        data = request.json
        user = User(
            first_name=data.get('firstname'),
            last_name=data.get('lastname'),
            email=data.get('email'),
            reg_no=data.get('reg_no'),
            role=data.get('role'),
            password=data.get('password')
        )
        user.save_to_db(session)

        response = {'message': 'Registration successful'}
        return jsonify(response), 200
    except Exception as e:
        session.rollback()
        return jsonify({'error': str(e)}), 500
    finally:
        session.close()

What could be the issue, any help will be appreciated

I tried to print the header and got:

Host: localhost:5000
Connection: keep-alive
Cache-Control: max-age=0
Sec-Ch-Ua: "Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
Cookie: Pycharm-119ea720=95741790-f49e-4011-8331-67c2c03dcc92; _ga=GA1.1.1648027930.1713378416; _ga_ZLVG7NETWG=GS1.1.1713532635.4.1.1713533069.0.0.0; _ga_1M7M0TRFHS=GS1.1.1713532635.4.1.1713533069.0.0.0; _ga_K62YRZRY27=GS1.1.1713532635.4.1.1713533069.0.0.0


---------
b''

looks like the request headers are correct, and the request body (request.data) is empty (b”).

I also tried to console.log(JSON.stringify(values)) and the form values are being fed correctly into the onfinish function

How to Position Text Labels at the Center of Arcs in a Radial Bar Chart using Vega?

I’m trying to create a radial bar chart using Vega, and I want to add text labels at the center of each arc in the chart to display the corresponding values. However, I’m having trouble positioning the text labels correctly within the arcs.

Here’s a simplified version of my Vega specification:

  {
      "type": "text",
      "name": "labels",
      "from": {"data": "table"},
      "encode": {
        "update": {
          "radius": {"scale": "chbands", "field": "category"},
          "x": {"signal": "width", "mult": 0.5},
          "y": {"signal": "height", "mult": 0.5},
          "dx": {"value": 0},
          "dy": {"value": 0},
          "text": {
            "signal": "isValid(datum['amount']) && datum['amount'] !== 0 ? datum['amount'] : ''"
          },
          "align": {"value": "center"},
          "baseline": {"value": "middle"},
          "theta": {
            "signal": "scale('theta', 0.5 * datum['r0'] + 0.5 * datum['r1'])"
          }
        }
      }
    }

Here is the screenshot of my current version.circular bar chart using vega

My expectation is that each text label should be centrally aligned with the arc path it belongs.

How to get multiple output as a parameter from tensor Flow prediction

I have a JSON like this

{
        "question": "bye for now",
        "intent": "greetings",
        "subintent": "bye",
        "answer": "Till next time"
    },
    {
        "question": "i must go",
        "intent": "greetings",
        "subintent": "bye",
        "answer": "see you soon!"
    }

Where I am training question using Fit and concatenating the intent and Subintent for a Output. But I need output in a different paramter for answer as well.

For example
If I search Bye

So right now its giving me intent : “greetings.bye” and score: 0.99
I need answers parameter with this as well

Training Code : https://collabedit.com/by7ct
Prediction Code : https://collabedit.com/7r3c2

While predicting we are saving the output unique values in a array while sending the text for prediction

const req = {
    body : {
    "intentArray": [
  'incident.info',
  'customercontext.info',
  'skillcontext.info',
  'greetings.bye',
  'greetings.hello'
],
    "text": "thats true"
}
}

As you see in the response top5Results I need answer as well related to that question, but right now its giving undefined

Tried the batch and dataset but didnt get the desired result

Select2 usage issue

my code

miku = [
        { id: 1, text: "Blue" },
        { id: 12, text: "David" },
        { id: 3, text: "Judy" },
        { id: 4, text: "Kate" },
        { id: 5, text: "John" },
    ];
    $(".search39").select2({
        language: 'zh-TW',
        placeholder: "第三人",
        containerCssClass: "search",
        maximumInputLength: 10,
        width: '100%',
        minimumInputLength: 0,
        tags: true,
        data: miku,
        matcher:
            function (params, data) {
                console.log(data)
                if ($.trim(params) === '') {
                    return data;
                }
                if (data.includes(params)) {
                    return data;
                }
                return null;
            }
    });

but it return me:
Blue
David
Judy
Kate
John
It only output the “text” properties, and it cannot output other properties(like “id”).
I want to search using the id.

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.0/select2.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
</head>
<body>
  <div>
    <select class="user"></select>
  </div>
  <script>
    $(function () {
      miku = [
        { id: 1, text: "Blue", note: "123" },
        { id: 12, text: "David" },
        { id: 3, text: "Judy" },
        { id: 4, text: "Kate" },
        { id: 5, text: "John" },
      ];
      $(".user").select2({
        language: 'zh-TW',
        width: '100%',
        maximumInputLength: 10,
        minimumInputLength: 0,
        tags: true,
        data: miku,
        matcher:
          function (params, data) {
            var term = params.term;
            console.log(data)
            if ($.trim(params.term) === '') {
              return data;
            }
            if (data.id.includes(term)) {
              console.log(data.id);
              return data;
            }
            return null;
          }
      });
    })
  </script>
</body>
</html>

This is the page I tested; it works fine. However, when added to the project, the output is different.
it can output otrher properties.
I also don’t understand why the same code results in different outcomes.

Unable to Update React-Rendered DOM Classes with jQuery

What I Tried:
Attempted to use jQuery to update classes within the DOM rendered by a React component.

Verified that the classes I’m targeting exist in the DOM by checking their length, which

consistently returns 0.
Ensured that both the React component and the jQuery code are correctly implemented and executed.

Expectations:

Ideally, when querying for the .wpgmp-map-data-container class using jQuery, I expected the length to be 1, indicating that the class exists in the DOM and can be manipulated accordingly.

facing problems sending a post request of arraylist of object as an input through the fronted(react.js)

I’m working on a full stack beginner project and did my backend in Springboot and the post request to add players to a team requests an arraylist of playerdto objects as it’s input, when testing through postman the json request usually looks like [{},{}] with playername and playerposition being the inputs inside the {} but I don’t know how to replicate this in my frontend through javascript, this is my javascript code as of now, you can skip through the other functions and can focus on the addplayer function alone I believe.

import React, { useState, useEffect } from "react";
import axios from "axios";
import './TeamDetailsPage.css'; // Import CSS file

const TeamDetailsPage = () => {
  const [teamdetails, setTeamDetails] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [teamName, setTeamName] = useState('');
  const [manager, setManager] = useState('');
  const [numPlayers, setNumPlayers] = useState(0); // Track the number of players to add
  const [playerInputs, setPlayerInputs] = useState([]); // Track player input fields
  const [showPlayerForm, setShowPlayerForm] = useState({});

  useEffect(() => {
    axios.get('http://localhost:8080/api/teamdetails/all')
      .then(response => {
        setTeamDetails(response.data);
        setLoading(false);
      })
      .catch(error => {
        console.error('Error fetching team details:', error);
        setError(error);
        setLoading(false);
      });
  }, []);

  const handleEditTeam = (teamDetailId) => {
    setTeamDetails(prevTeamDetails => (
      prevTeamDetails.map(team => (
        team.id === teamDetailId ? { ...team, editing: true } : team
      ))
    ));
  };

  const handleUpdateTeam = (teamDetailId, updatedTeamDetails) => {
    axios.put(`http://localhost:8080/api/teamdetails/${teamDetailId}/update`, updatedTeamDetails)
      .then(response => {
        console.log('Team details updated:', response.data); // Log the updated data
        setTeamDetails(prevTeamDetails => (
          prevTeamDetails.map(team => (
            team.id === teamDetailId ? { ...response.data, editing: false } : team
          ))
        ));
      })
      .catch(error => {
        console.error('Error updating team details:', error);
      });
  };

  const handleCreateTeam = () => {
    setShowForm(true);
  };

  const handleSubmit = () => {
    const newTeam = {
      teamName: teamName,
      manager: manager,
      players: playerInputs.map(playerInput => ({
        playerName: playerInput.playerName,
        playerPosition: playerInput.playerPosition
      }))
    };
  
    axios.post('http://localhost:8080/api/teamdetails/create', newTeam)
      .then(response => {
        console.log('New team created:', response.data);
        setShowForm(false); // Close the form after submitting
        // Reload the team details after creating the new team
        axios.get('http://localhost:8080/api/teamdetails/all')
          .then(response => {
            setTeamDetails(response.data);
          })
          .catch(error => {
            console.error('Error fetching team details:', error);
            setError(error);
          });
      })
      .catch(error => {
        console.error('Error creating new team:', error);
      });
  };  

  const handleDeleteTeam = (teamDetailId) => {
    axios.delete(`http://localhost:8080/api/teamdetails/${teamDetailId}/delete`)
      .then(() => {
        console.log('Team deleted:', teamDetailId);
        // Remove the deleted team from the list
        setTeamDetails(prevTeamDetails => (
          prevTeamDetails.filter(team => team.id !== teamDetailId)
        ));
      })
      .catch(error => {
        console.error('Error deleting team:', error);
      });
  };

  const handleTogglePlayerForm = (teamId) => {
    setShowPlayerForm(prevState => ({
      ...prevState,
      [teamId]: !prevState[teamId]
    }));
    // Reset input fields when opening the form
    setPlayerInputs([]);
  };

  const handleAddPlayer = () => {
    // Create input fields for player names and positions based on the number of players
    const newPlayerInputs = Array.from({ length: numPlayers }, (_, index) => ({
      playerName: '',
      playerPosition: '',
      id: index // Add unique ID for tracking purposes
    }));
    setPlayerInputs(newPlayerInputs);
  };

  const handleRemovePlayer = (id) => {
    // Remove player input field based on its unique ID
    const updatedPlayerInputs = playerInputs.filter(playerInput => playerInput.id !== id);
    setPlayerInputs(updatedPlayerInputs);
  };

  const handlePlayerNameChange = (e, id) => {
    // Update player name based on its unique ID
    const updatedPlayerInputs = playerInputs.map(playerInput => {
      if (playerInput.id === id) {
        return { ...playerInput, playerName: e.target.value };
      }
      return playerInput;
    });
    setPlayerInputs(updatedPlayerInputs);
  };

  const handlePlayerPositionChange = (e, id) => {
    // Update player position based on its unique ID
    const updatedPlayerInputs = playerInputs.map(playerInput => {
      if (playerInput.id === id) {
        return { ...playerInput, playerPosition: e.target.value };
      }
      return playerInput;
    });
    setPlayerInputs(updatedPlayerInputs);
  };

  const handleAddPlayerToTeam = (teamId) => {
    const players = playerInputs.map(playerInput => ({
      playerName: playerInput.playerName,
      playerPosition: playerInput.playerPosition
    }));

    axios.post(`http://localhost:8080/api/teamdetails/${teamId}/addplayers`, {
      players: players
    })
      .then(response => {
        console.log('Players added to team:', response.data);
        // Optionally, update the state to reflect the change
        // For example, refetch team details
        axios.get(`http://localhost:8080/api/teamdetails/all`)
          .then(response => {
            setTeamDetails(response.data);
          })
          .catch(error => {
            console.error('Error fetching team details:', error);
            setError(error);
          });
      })
      .catch(error => {
        console.error('Error adding players to team:', error);
      });
  };

  return (
    <div className="team-details-container">
      <div className="team-topbar">
        <h1>Teams</h1>
        <button className="create-button" onClick={handleCreateTeam}>Create Team</button>
      </div>
      {showForm && (
        <div className="team-container">
          <div className="edit-form">
            {/* Input fields for creating team details */}
            <input
              type="text"
              value={teamName}
              onChange={(e) => setTeamName(e.target.value)}
              placeholder="Enter team name"
            />
            <input
              type="text"
              value={manager}
              onChange={(e) => setManager(e.target.value)}
              placeholder="Enter manager name"
            />
            {/* Input field for number of players */}
            <input
              type="number"
              value={numPlayers}
              onChange={(e) => setNumPlayers(e.target.value)}
              placeholder="Enter number of players"
            />
            {/* Add button to dynamically generate player input fields */}
            <button onClick={handleAddPlayer}>Add Player</button>
            {/* Display input fields for player names and positions */}
            {playerInputs.map((playerInput) => (
              <div key={playerInput.id}>
                <input
                  type="text"
                  value={playerInput.playerName}
                  onChange={(e) => handlePlayerNameChange(e, playerInput.id)}
                  placeholder="Enter player name"
                />
                <input
                  type="text"
                  value={playerInput.playerPosition}
                  onChange={(e) => handlePlayerPositionChange(e, playerInput.id)}
                  placeholder="Enter player position"
                />
                <button onClick={() => handleRemovePlayer(playerInput.id)}>Remove</button>
              </div>
            ))}
            {/* Submit button to add the team */}
            <button className="submit-button" onClick={handleSubmit}>Submit</button>
          </div>
        </div>
      )}
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>Error: {error.message}</p>
      ) : (
        teamdetails.map(team => (
          <div key={team.id} className="team-container">
            {team.editing ? (
              <div className="edit-form">
                {/* Input fields for editing team details */}
                <input
                  type="text"
                  value={team.teamName}
                  onChange={(e) => setTeamDetails(prevTeamDetails => (
                    prevTeamDetails.map(item => (
                      item.id === team.id ? { ...item, teamName: e.target.value } : item
                    ))
                  ))}
                />
                {/* Add similar input fields for manager, players, etc. */}
                <input
                  type="text"
                  value={team.manager}
                  onChange={(e) => setTeamDetails(prevTeamDetails => (
                    prevTeamDetails.map(item => (
                      item.id === team.id ? { ...item, manager: e.target.value } : item
                    ))
                  ))}
                />
                {/* Add input fields for player names and positions */}
                <button className="update-button" onClick={() => handleUpdateTeam(team.id, team)}>Update</button>
              </div>
            ) : (
              <>
                <h2 className="team-name">{team.teamName}</h2>
                <p className="manager">Manager: {team.manager}</p>
                {/* Display player details */}
                <ul className="players-list">
                  {team.players.map(player => (
                    <li key={player.id} className="player">
                      {player.playerName} - {player.playerPosition}
                    </li>
                  ))}
                </ul>
                <button className="edit-button" onClick={() => handleEditTeam(team.id)}>Edit</button>
                <button className="delete-button" onClick={() => handleDeleteTeam(team.id)}>Delete</button>
                {/* Add button to toggle player form */}
                <button className="add-player-button" onClick={() => handleTogglePlayerForm(team.id)}>Add Player</button>
                {/* Add player form */}
                {showPlayerForm[team.id] && (
                  <form onSubmit={(e) => { e.preventDefault(); handleAddPlayerToTeam(team.id); }}>
                    {playerInputs.map((playerInput, index) => (
                      <div key={index}>
                        <input
                          type="text"
                          value={playerInput.playerName}
                          onChange={(e) => handlePlayerNameChange(e, playerInput.id)}
                          placeholder="Enter player name"
                        />
                        <input
                          type="text"
                          value={playerInput.playerPosition}
                          onChange={(e) => handlePlayerPositionChange(e, playerInput.id)}
                          placeholder="Enter player position"
                        />
                      </div>
                    ))}
                    <button type="submit">Submit</button>
                  </form>
                )}
              </>
            )}
          </div>
        ))
      )}
    </div>
  );       
};

export default TeamDetailsPage;

the error I recieve is:
JSON parse error: Cannot deserialize value of type `java.util.ArrayList<com.footballleague.footballleague.dto.PlayerDto>` from Object value (token `JsonToken.START_OBJECT`)]
this is my backend code:
service impl:

@Override
public TeamDetails addPlayersToTeam(Long teamId, List<PlayerDto> playerDtoList) {
    TeamDetails team = teamDetailsRepository.findById(teamId)
            .orElseThrow(() -> new ResourceNotFoundException("Team not found with id: " + teamId));

    List<Player> players = new ArrayList<>();
    for (PlayerDto playerDto : playerDtoList) {
        Player player = PlayerMapper.mapToPlayer(playerDto);
        player.setTeamDetails(team); // Set the team for each player
        players.add(player);
    }

    team.getPlayers().addAll(players); // Ensure bidirectional relationship is managed
    team = teamDetailsRepository.save(team);//line 45
    return team;
}

controller:

@RequestMapping("/api/teamdetails")

@PostMapping("/{teamId}/addplayers")
    public ResponseEntity<TeamDetailsDto> addPlayersToTeam(@PathVariable("teamId") Long teamId, @RequestBody List<PlayerDto> playerDtoList) {
        TeamDetails updatedTeamDetails = teamDetailsService.addPlayersToTeam(teamId, playerDtoList);//line 30
        TeamDetailsDto updatedTeamDetailsDto = TeamDetailsMapper.mapToTeamDetailsDto(updatedTeamDetails);
        return new ResponseEntity<>(updatedTeamDetailsDto, HttpStatus.OK);
    }

How to restore the folder hierarchy from the files list of file uploads?

When doing file upload, select the folder and get the files list. But there is no directory hierarchy of folders.The following array can be obtained from the list of files. How can you restore the folder structure by traversing the file’s webkitRelativePath? Thanks very much!
The following array is:

const files = [
  {
    file: {
      webkitRelativePath: ''
    },
    name: '测试文件.text'
  },
  {
    file: {
      webkitRelativePath: 'test/前端文件.PDF'
    },
    name: '前端文件.PDF'
  },
  {
    file: {
      webkitRelativePath: 'test/x/第一次上传.mp4'
    },
    name: '第一次上传.mp4'
  },
  {
    file: {
      webkitRelativePath: 'test/x/第二次上传.mp4'
    },
    name: '第二次上传.mp4'
  }
]

Through a function to be

const directory = [
  {
    file: {
      webkitRelativePath: ''
    },
    Type: 'FILE',
    name: '测试文件.text'
  },
  {
    Type: 'DIR',
    name: 'test',
    subdirectory: [
      {
        file: {
          webkitRelativePath: 'test/前端文件.PDF'
        },
        Type: 'FILE',
        name: '前端文件.PDF'
      },
      {
        Type: 'DIR',
        name: 'x',
        subdirectory: [
          {
            file: {
              webkitRelativePath: 'test/x/第一次上传.mp4'
            },
            Type: 'FILE',
            name: '第一次上传.mp4'
          },
          {
            file: {
              webkitRelativePath: 'test/x/第二次上传.mp4'
            },
            Type: 'FILE',
            name: '第二次上传.mp4'
          }
        ]
      }
    ]
  },
]

Logout error: TypeError: res.setHeader is not a function using Next.js

I’ve recently started diving into Next.js, but I’ve hit a roadblock while working on the logout functionality. Despite researching similar issues, I’m still unable to resolve the error I’m encountering. Let me provide you with more context to better understand the problem.

Summaries Error:

Error Message: TypeError: res.setHeader is not a function
File: src/app/api/auth/logout/route.tsx
Probable Cause:
The error suggests that there’s an issue with the res object within the logout route. It seems like the res object doesn’t have the expected setHeader function. This typically indicates a mismatch between the expected and actual object types.

path: src/app/api/auth/logout/route.tsx

export async function GET(req: NextApiRequest, res: NextApiResponse) {
    try {
      res.setHeader(
        "Set-Cookie",
        `${COOKIE_NAME}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT`
      );
      res.writeHead(302, { Location: "/login" });
      res.end();
    } catch (error) {
      console.error("Logout error:", error);
      res.status(500).json({ message: "Internal Server Error" });
    }
}

path: src/app/components/LeftPanel.tsx

import React from 'react';
import { Button } from "../../components/ui/button"
import './style.css';
import { useRouter } from 'next/navigation';
const LeftPanel: React.FC = () => {
  const { push } = useRouter();
  const handleLogout = async () => {
    try {
      const response = await fetch('/api/auth/logout', {
        method: 'GET',
      });
      if (response.ok) {
        window.alert('Logout successful! Click OK to go to the login page.');
        console.log('response', response);
        push('/login');
      }
    } catch (error) {
      console.error("Logout error:", error);
      // Handle any potential errors
    }
  };
  return (
    <div className="left-panel">
      <Button onClick={handleLogout}>Logout</Button>
    </div>
  );
};

export default LeftPanel;

FULL ERROR

Logout error: TypeError: res.setHeader is not a function
    at GET (webpack-internal:///(rsc)/./src/app/api/auth/logout/route.tsx:9:13)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:53452
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:140:36
    at NoopContextManager.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:7062)
    at ContextAPI.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:518)
    at NoopTracer.startActiveSpan (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:18093)      
    at ProxyTracer.startActiveSpan (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:18854)     
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:122:103
    at NoopContextManager.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:7062)
    at ContextAPI.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:518)
    at NextTracerImpl.trace (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:122:28)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:46261
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:39188)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:45368
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:37583)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:45330
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at e_.execute (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:44777)
    at e_.handle (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:54711)
    at doRender (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1377:60)
    at cacheEntry.responseCache.get.routeKind (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1599:34)
    at ResponseCache.get (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverresponse-cacheindex.js:49:26)
    at DevServer.renderToResponseWithComponentsImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1507:53)   
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1002:121
    at NextTracerImpl.trace (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:105:20)
    at DevServer.renderToResponseWithComponents (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1002:41)       
    at DevServer.renderPageComponent (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1924:35)
    at async DevServer.renderToResponseImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1962:32)
    at async DevServer.pipeImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:920:25)
    at async NextNodeServer.handleCatchallRenderRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistservernext-server.js:272:17)    at async DevServer.handleRequestImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:816:17)
    at async C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverdevnext-dev-server.js:339:20
    at async Span.traceAsyncFn (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdisttracetrace.js:154:20)
    at async DevServer.handleRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverdevnext-dev-server.js:336:24)
    at async invokeRender (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:174:21)
    at async handleRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:353:24)
    at async requestHandlerImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:377:13)
    at async Server.requestListener (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibstart-server.js:141:13)
 ⨯ TypeError: res.status is not a function
    at GET (webpack-internal:///(rsc)/./src/app/api/auth/logout/route.tsx:16:13)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:53452
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:140:36
    at NoopContextManager.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:7062)
    at ContextAPI.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:518)
    at NoopTracer.startActiveSpan (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:18093)      
    at ProxyTracer.startActiveSpan (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:18854)     
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:122:103
    at NoopContextManager.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:7062)
    at ContextAPI.with (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompiled@opentelemetryapiindex.js:1:518)
    at NextTracerImpl.trace (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:122:28)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:46261
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:39188)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:45368
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at Object.wrap (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:37583)
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:45330
    at AsyncLocalStorage.run (node:async_hooks:338:14)
    at e_.execute (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:44777)
    at e_.handle (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistcompilednext-serverapp-route.runtime.dev.js:6:54711)
    at doRender (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1377:60)
    at cacheEntry.responseCache.get.routeKind (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1599:34)
    at ResponseCache.get (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverresponse-cacheindex.js:49:26)
    at DevServer.renderToResponseWithComponentsImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1507:53)   
    at C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1002:121
    at NextTracerImpl.trace (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibtracetracer.js:105:20)
    at DevServer.renderToResponseWithComponents (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1002:41)       
    at DevServer.renderPageComponent (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1924:35)
    at async DevServer.renderToResponseImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:1962:32)
    at async DevServer.pipeImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:920:25)
    at async NextNodeServer.handleCatchallRenderRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistservernext-server.js:272:17)    at async DevServer.handleRequestImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverbase-server.js:816:17)
    at async C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverdevnext-dev-server.js:339:20
    at async Span.traceAsyncFn (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdisttracetrace.js:154:20)
    at async DevServer.handleRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverdevnext-dev-server.js:336:24)
    at async invokeRender (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:174:21)
    at async handleRequest (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:353:24)
    at async requestHandlerImpl (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibrouter-server.js:377:13)
    at async Server.requestListener (C:UsersDennisOneDriveDesktoploginNextloginnextnode_modulesnextdistserverlibstart-server.js:141:13)
 GET /api/auth/logout 500 in 549ms

Remove the extra space on the first page within the printing area

I have two simple questions. I want to print a page with these contents. The printing area for the first page is like this.

enter image description here

and for the second page

enter image description here

My first question is: As you see, the first page has a different distance from the top than the second page (and other pages). However, I don’t want this difference; I want the exact same distance.

And my second question is: Is there any way to show the print date and time only on the first page?

this is my css and js code

  window.print();
@media print {
  /* Hides the entire body content initially */
  body {
    margin: 0;
    padding: 0;
    visibility: hidden;
    -webkit-print-color-adjust: exact; /* Ensure colors appear correctly when printing */
  }

  /* Shows only the specified element and keeps other elements hidden */
  #ride-receipts {
    visibility: visible; /* Makes it visible */
    gap: 60px; /* Adds the specified gap */
    width: 100%; /* Sets the full width */
  }

  #ride-receipts > div {
    break-inside: avoid;
  }

  .drawer {
    display: none;
  }
}

@page {
  size: auto;
  margin-bottom: 0;
}

why the rendering is not working its a reference error

ReferenceError: E:levelx_Express.jsmini_projectviewslogin.ejs:16
    14|     <form action="/login" method="post">

    15|       <h2>Login</h2>

 >> 16|       <% if (error ) { %>

    17|         <small style="color: red;"><%=  error  %></small>

    18|     <% }%>

    19|       <div class="input-field">


error is not defined
    at eval ("E:\levelx_Express.js\mini_project\views\login.ejs":12:8)
    at login (E:levelx_Express.jsmini_projectnode_modulesejslibejs.js:703:17)
    at tryHandleCache (E:levelx_Express.jsmini_projectnode_modulesejslibejs.js:274:36)
    at exports.renderFile [as engine] (E:levelx_Express.jsmini_projectnode_modulesejslibejs.js:491:10)
    at View.render (E:levelx_Express.jsmini_projectnode_modulesexpresslibview.js:135:8)
    at tryRender (E:levelx_Express.jsmini_projectnode_modulesexpresslibapplication.js:657:10)
    at Function.render (E:levelx_Express.jsmini_projectnode_modulesexpresslibapplication.js:609:3)
    at ServerResponse.render (E:levelx_Express.jsmini_projectnode_modulesexpresslibresponse.js:1048:7)
    at E:levelx_Express.jsmini_projectserver.js:34:9
    at Layer.handle [as handle_request] (E:levelx_Express.jsmini_projectnode_modulesexpresslibrouterlayer.js:95:5)

iam trying embed the condition to check the username and password valid or not in alogin form