i have API and i have error whene i send multiple images to client the req have one image only. i use noodjs

const express = require("express");
const asyncHandler = require("express-async-handler");
const Image = require('../models/Image');
const router = express.Router();
const multer = require('multer');
const sharp = require('sharp');

router.get("/", asyncHandler(async (req, res) => {

    //const images = await Image.findById('');
    const imagesInfo = await Image.find();
    const imagesBuffers = imagesInfo.map((img) => img.data);

    const promises = imagesBuffers.map((buffer) =>
        sharp(buffer).toFormat('jpeg').toBuffer()
    );
    Promise.all(promises)
        .then((outputBuffers) => {
            // تحديد نوع المحتوى كصورة
            res.contentType('image/jpeg');
            // إرسال بيانات الصور كجزء من الاستجابة
            outputBuffers.forEach((outputBuffer) => {
                res.write(outputBuffer, 'binary');
            });

            res.end();
        })
        .catch((err) => {
            console.error('Error:', err);
            res.status(500).send('Error.');
        });
}));
module.exports = router;

I have a buffer array and I want to convert it into images and send it to the user. This code has a problem. I don’t know what it is. It sends only one image.

Medicine products fetching process is initiated, but the data is not available until the request completes successfully

Problem Summary:

The “Featured” component is not initially displaying the medicine products data because the medicine products are not yet fetched from the API. The component is re-rendering as the medicine products fetching process is initiated, but the data is not available until the request completes successfully.

Detailed Analysis:

Initial Rendering: The “Featured” component renders without displaying the medicine products data because the initial state of the medicineProducts array is empty.

Fetching Process Initiation: The FETCH_MEDICINE_PRODUCTS_REQUEST action is dispatched, triggering the asynchronous process of fetching medicine products from the API.

State Update and Re-render: The reducer updates the isLoading state to true, indicating that data is being fetched. The component re-renders due to this state change, but the medicine products data is still not available from the API.

Extension Loading: An extension, possibly related to loading or data fetching, is loaded. This suggests that additional resources or functionalities are being prepared to handle the incoming data.

Resolution:

The problem will be resolved once the medicine products fetching process completes successfully and the FETCH_MEDICINE_PRODUCTS_SUCCESS action is dispatched. The reducer will update the medicineProducts state with the fetched data, and the component will re-render again, displaying the updated data.
here is // Featured.js

// Featured.js
import { connect } from "react-redux";
import React, { useEffect } from "react";
import Product from "./Product"; // Assuming the Product component is in the same directory
import { fetchMedicineProductsRequest } from "../redux/actions/productAction";

function Featured({ medicineProducts, isLoading, error, fetchMedicineProducts }) {
  useEffect(() => {
    console.log('Component mounted');
    fetchMedicineProducts();
  }, [fetchMedicineProducts]);
  console.log("Component: Rendering", { isLoading, error, medicineProducts });
  return (
    <div className="featured-container">
      <div className="container-header">
        <h2>Featured Products</h2>
        <div className="content-link">
          <a className="link-underline" href="#home">
            View All
          </a>
        </div>
      </div>
      <div className="featured-content">
        {isLoading ? (
          <div>Fetching Featured Products...</div>
        ) : error ? (
          <div>Error: {error.message}</div>
        ) : (
          <div className="products">
            {medicineProducts.map((product) => (
              <Product
                key={product.id}
                subtitle="Essential for Women/Men"
                title={product.name}
                desc={product.description}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

const mapStateToProps = (state) => ({
  medicineProducts: state.medicineProducts.medicineProducts,
  isLoading: state.medicineProducts.isLoading,
  error: state.medicineProducts.error,
});

const mapDispatchToProps = {
  fetchMedicineProducts: fetchMedicineProductsRequest,
};

export default connect(mapStateToProps, mapDispatchToProps)(Featured);

and this is // productAction.js

import {
  FETCH_MEDICINE_PRODUCTS_REQUEST,
  FETCH_MEDICINE_PRODUCTS_SUCCESS,
  FETCH_MEDICINE_PRODUCTS_FAILURE,
} from '../types';
import axios from '../../axiosConfig';

export const fetchMedicineProductsRequest = () => ({
  type: FETCH_MEDICINE_PRODUCTS_REQUEST,
});

export const fetchMedicineProductsSuccess = (data) => ({
  type: FETCH_MEDICINE_PRODUCTS_SUCCESS,
  payload: data,
});

export const fetchMedicineProductsFailure = (error) => ({
  type: FETCH_MEDICINE_PRODUCTS_FAILURE,
  payload: error,
});

export const fetchMedicineProducts = () => async (dispatch) => {
  console.log("Action: fetchMedicineProductsRequest");
  dispatch(fetchMedicineProductsRequest());

  try {
    const response = await axios.get('/api/products/');
    console.log("Action: Successful response", response.data);

    if (response.status !== 200) {
      throw new Error('Error!');
    }

    dispatch(fetchMedicineProductsSuccess(response.data.products));
  } catch (error) {
    console.log("Action: Error", error.message);
    dispatch(fetchMedicineProductsFailure(error.message));
  }
};

// productReducer.js

// productReducer.js
import * as types from '../types';

const initialState = {
  medicineProducts: [],
  isLoading: false,
  error: null,
};

const medicineProductsReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.FETCH_MEDICINE_PRODUCTS_REQUEST:
      console.log("Reducer: FETCH_MEDICINE_PRODUCTS_REQUEST");
      return { ...state, isLoading: true, error: null };

    case types.FETCH_MEDICINE_PRODUCTS_SUCCESS:
      console.log("Reducer: FETCH_MEDICINE_PRODUCTS_SUCCESS", action.payload);
      return { ...state, isLoading: false, medicineProducts: action.payload };

    case types.FETCH_MEDICINE_PRODUCTS_FAILURE:
      
      return { ...state, isLoading: false, error: action.payload };

    default:
      return state;
  }
};

export default medicineProductsReducer;

Postman API call:

enter image description here

The problem will be resolved once the medicine products fetching process completes successfully and the FETCH_MEDICINE_PRODUCTS_SUCCESS action is dispatched. The reducer will update the medicineProducts state with the fetched data, and the component will re-render again, displaying the updated data.

Meteor/Vue: Display result of search

I would like to add a search field to my app and show all articles from my Collection that match the entered value. The searchArticles method is called but the values are not shown as defined below the search field. What am I doing wrong?

<script setup>
import { ref } from 'vue';
import { ArticlesCollection } from '../../db/ArticlesCollection';
import Article from '../components/Article.vue';
import { subscribe } from 'vue-meteor-tracker';

const newArticle = ref('');
let matchingArticles = [];
const searchArticles = () => {
  matchingArticles = ArticlesCollection.find({ text: newArticle.value });
};

subscribe('articles');
</script>

<template>
  <form @submit.prevent="searchArticles">
    <input
      class="border border-gray-300 rounded-md py-2 px-4 mr-2 text-gray-600 text-sm focus:outline-none focus:border-gray-400 focus:ring-0"
      type="text"
      placeholder="Type to add new articles"
    />
    <button
      class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded"
      type="submit"
    >
      Add Article
    </button>
  </form>
  <ul class="list-disc list-inside p-4">
    <Article
      v-for="article of matchingArticles"
      :key="article._id"
      :article="article"
    />
  </ul>
</template>


How to learn computer languages [closed]

How to arrange the order of learning reasonably

I look forward to learning more

I look forward to being the person I want to be, to be able to realize my dreams, and to be able to contribute to the country and society

I want to have fun learning every day

Struggling with turn based game in JavaScript

I am building a turn-based battle sequence in JavaScript that runs in the console of a browser.

I set my for-loop to keep going until the boss health is no longer greater than 0, then try to build if statements within the code for each turn. The problem is the for loop will continue running or when I reassign the player health inside an if statement, the scope is too far in and I can’t return it.

One thing I’ve tried is a for loop where the assigned int would designate an event, but with if statements it skips numbers and does not pause. I need it to pause.

Here’s the code:

for(let attackTurn = 0; bossHealth > 0; attackTurn++) {

    
    if (attackTurn%2 ==1) {
            attackChoice = prompt("1 or 2?");

            if(attackChoice == 1) {
                bossHealth = bossHealth - 30;
                console.log(bossHealth);
            } else if (attackChoice == 2) {
                bossHealth = bossHealth - 30;
                console.log(bossHealth);
        
            }
    }
}

I think the for loop idea is right but I just need to know how to implement it properly.

Express.js – pdf2pic generated PNG image from PDFkit buffer stream comes out corruped

I’ve created Express.js HTTP server that listens for POST request of body containing text. This text then used by PDFkit library to generate PDF with the text as body.

I’m not saving the PDF on machine but instead I piping it to the stream.

Finally – on stream finalized – the buffer is then passed to pdf2pic for conversion to PNG image. However after responding back to client and saved on client machine, it comes out corrupted (file size too small).

I’ve tried to debug and pinpoint the issue, but with no luck. Maybe the buffer is incomplete or prematurely sent?

Here is front-end (client) code of axios request (I’m using **FileSaver **saveAs function to save PNG image:

const requestData = {
  text: gift.value.text,
};

const config = {
  headers: {
    'Content-Type': 'application/json'
  },
  responseType: 'arraybuffer'
};

axios.post('/png', JSON.stringify(requestData), config)
  .then(response => {
     const blob = new Blob([await res.data], { type: 'image/png' })
     await saveAs(blob, fileName)
  })
  .catch(error => {
    // Handle errors
    console.error(error);
  });

And here is my server-side code of Express.js POST request response with the PNG image:

import type { Request, Response } from 'express'
import express from 'express'
import bodyParser from 'body-parser'
import * as fs from 'fs'
import * as stream from 'stream'
import PDFDocument from 'pdfkit'
import { fromBuffer } from 'pdf2pic'

const router = express.Router()

router.post('/png', bodyParser.json(), async (req: Request, res: Response) => {
  const { text } = req.body

  if (!text) {
    return res.status(400).json({ error: 'Text is required in the request body' })
  }

  // Create a PDF document
  const pdfDoc = new PDFDocument()

  // Create a writable stream for the PDF content
  const pdfStream = new stream.Writable()
  const pdfBuffer: Buffer[] = []

  pdfStream._write = (chunk, encoding, callback) => {
    pdfBuffer.push(chunk)
    callback()
  }

  pdfStream.on('finish', async () => {
    const pdf2pic = fromBuffer(Buffer.concat(pdfBuffer), {
      density: 100,
      saveFilename: 'output',
      savePath: './',
      format: 'png',
      width: 600,
      height: 800
    })

    const result = await pdf2pic(1) // Convert the first page

    console.log(result)
    // Send the PNG image back to the client
    res.contentType('image/png')
    res.send(result)

    // Clean up the temporary files
    fs.unlinkSync('./')
  })

  pdfDoc.pipe(pdfStream)
  pdfDoc.text(text)
  pdfDoc.end()
})

export { router as services }

And here is a screenshot of the corrupt image file:

enter image description here

Any idea how to fix this issue?

getting 429 (Too many requests) ERROR while fetching data in useState(), how do I fix it?

I’m building a project with vite + react app.
I fetched data in useEffect() and got the following error in console:
GET https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple 429 (Too Many Requests)

Here’s my code :

import React,{useState,useEffect} from 'react'

function QuizMain() {
    const[data,setData] = useState()
    useEffect(()=> {
        fetch("https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple")
        .then((res)=> res.json())
        .then((data)=>console.log(data))
    },[])
  return (
    <div >...</div>
  )
}

I set the second argument in useEffect(function,[]), why is it fetching multiple times? How to I fix it? I’m a newbie!

I am expecting to fetch data only one time on render and update the state.

firebase type error Cannot read properties of undefined appVerificationDisabledForTesting and verify what is wrong in my code i’m getting this error

this is my code for generating otp:

import React, { useState } from "react";
import Layout from "./../../components/Layout/Layout";
import toast from "react-hot-toast";
import OtpInput from "otp-input-react";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import { RecaptchaVerifier, signInWithPhoneNumber } from "firebase/auth";
import { Auth } from "../../firebase-config";

const ForgotPassword = () => {
  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState("");
  const [showOtpInterface, setShowOtpInterface] = useState(false);

  const onCaptchVerify = () => {
    try {
      // Create a new RecaptchaVerifier
      if (!window.recaptchaVerifier) {
        window.recaptchaVerifier = new RecaptchaVerifier(
          "recaptcha-container",
          {
            size: "invisible",
            callback: (response) => {
              onSignUp();
            },
            "expired-callback": () => {
              // Handle expiration if needed
            },
          },
          Auth
        );
      }
    } catch (error) {
      console.log(error);
    }
  };

  const onSignUp = () => {
    onCaptchVerify();
    const appVerifier = window.recaptchaVerifier;
    const formatStr = `+${phone}`;

    signInWithPhoneNumber(Auth, formatStr, appVerifier)
      .then((confirmationResult) => {
        window.confirmationResult = confirmationResult;
        setShowOtpInterface(true);
        toast.success("OTP sent successfully");
      })
      .catch((error) => {
        toast.error("OTP sent failed");
        console.log(error);
      });
  };

  const onOtpVerify = () => {
    window.confirmationResult
      .confirm(otp)
      .then(async (res) => {
        console.log(res);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  return (
    <Layout title={"Forgot Password - Ecommerce APP"}>
      <div className="form-container">
        <div>
          <h4 className="title">RESET PASSWORD</h4>
          <div id="recaptcha-container"></div>
          {showOtpInterface ? (
            <>
              <label htmlFor="ph">Enter Your OTP</label>
              <OtpInput
                OTPLength={6}
                otpType="number"
                disabled={false}
                autoFocus
                value={otp}
                onChange={setOtp}
              />
              <button
                type="submit"
                className="btn btn-primary mt-3"
                onClick={onOtpVerify}
              >
                Verify
              </button>
            </>
          ) : (
            <>
              <label htmlFor="email">Enter your registered phone number</label>
              <PhoneInput country={"in"} value={phone} onChange={setPhone} />
              <button
                type="submit"
                onClick={onSignUp}
                className="btn btn-primary mt-3"
              >
                Continue
              </button>
            </>
          )}
        </div>
      </div>
    </Layout>
  );
};

export default ForgotPassword;

Error Details:
I’m specifically struggling with the RecaptchaVerifier and appVerificationDisabledForTesting property. The error suggests that the properties are undefined, even though they should be accessible according to the Firebase documentation.
and error looks like this:

    at _verifyPhoneNumber (phone.ts:186:1)
    at signInWithPhoneNumber (phone.ts:108:1)
    at onSignUp (ForgotPasssword.js:43:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)
    at react-dom.development.js:9288:1
    at batchedUpdates$1 (react-dom.development.js:26140:1)
    at batchedUpdates (react-dom.development.js:3991:1)
    at dispatchEventForPluginEventSystem (react-dom.development.js:9287:1)
    at dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay (react-dom.development.js:6465:1)
    at dispatchEvent (react-dom.development.js:6457:1)
    at dispatchDiscreteEvent (react-dom.development.js:6430:1)

TypeError: Cannot read properties of undefined (reading 'appVerificationDisabledForTesting')
    at new RecaptchaVerifier (recaptcha_verifier.ts:114:1)
    at onCaptchVerify (ForgotPasssword.js:19:1)
    at onSignUp (ForgotPasssword.js:39:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
    at invokeGuardedCallback (react-dom.development.js:4277:1)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
    at executeDispatch (react-dom.development.js:9041:1)
    at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
    at processDispatchQueue (react-dom.development.js:9086:1)
    at dispatchEventsForPlugins (react-dom.development.js:9097:1)
    at react-dom.development.js:9288:1
    at batchedUpdates$1 (react-dom.development.js:26140:1)
    at batchedUpdates (react-dom.development.js:3991:1)
    at dispatchEventForPluginEventSystem (react-dom.development.js:9287:1)
    at dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay (react-dom.development.js:6465:1)
    at dispatchEvent (react-dom.development.js:6457:1)
    at dispatchDiscreteEvent (react-dom.development.js:6430:1)

im using "firebase": "^10.6.0",

Request for Help:
I’m reaching out to the community for any insights or suggestions on resolving this issue. If anyone has encountered similar problems with Firebase Phone Authentication or has expertise in troubleshooting such errors, your assistance would be highly appreciated!

Import behaviour with Typescript

How are we able to import Request, Response, Express interface from express

import express, {Express, Request, Response} from 'express';

Checked the types declaration file we are only exporting function as default

This is the definition of index.d.ts file in the official lib

declare function e(): core.Express;

declare namespace e {
    interface Express extends core.Express {}
    interface Request<
        P = core.ParamsDictionary,
        ResBody = any,
        ReqBody = any,
        ReqQuery = core.Query,
        Locals extends Record<string, any> = Record<string, any>,
    > extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}

    interface Response<
        ResBody = any,
        Locals extends Record<string, any> = Record<string, any>,
    > extends core.Response<ResBody, Locals> {}
}

export = e;
  • As the namespace is using the same name as function all the properties merged with function which means we can access the interface from function like this express.Request not as named imports as shown above?

Am i missing something?

Expected

import express from 'express';
let {Express, Request, Response} = express

i18n with Next.js 14 and app directory / App Router

When attempting to localize the app project, I face an issue where checking the first page (“/”) leads to a 404 error. I have two languages configured:

/ -> 404
/en -> English
/de -> German

It should be

/ -> English
/en -> English
/de -> German

I want the root (“/”) to display the English version and (“/de”) to show the German version.
How can I appropriately handle this in the app directory?

I’m aiming to achieve the same functionality as demonstrated in carlogino, but unfortunately, I’m encountering issues, and the solution isn’t working for me.

    "node":"18.17.0",     
    "next": "^14.0.3",
    "react": "18.2.0",
    "i18next": "^23.7.6",
    "i18next-browser-languagedetector": "^7.2.0",
    "i18next-resources-to-backend": "^1.2.0",

enter image description here

Receive net::ERR_FILE_NOT_FOUND message but working image link shows in HTML

I am putting together a weather app suing weatherapi.
I can retrieve the general weather but I get a net::ERR_FILE_NOT_FOUND message for the icon, however the icon url shows in the HTML and is working when I open it in a new tab.
I also receive undefined for the temp and feelslike queries.

Any help would be appreciated please.

My javascript code below:

const 
    search = document.getElementById("keyword"),
    submitBtn = document.getElementById("submit-button"),
    cityName = document.getElementById("city"),
    showDate = document.getElementById("date"),
    showTime = document.getElementById("time"),
    showWeather = document.querySelector("#weather h1"),
    weatherPic = document.querySelector("#weather div"),
    temperature = document.querySelector("#temperature"),
    feelsLike = document.querySelector("#feels-like");
    
async function getWeather(e) {
    const keyword = document.querySelector("#keyword").value;
    e.preventDefault();
    console.log(keyword);
    const response = await fetch(`http://api.weatherapi.com/v1/current.json?key=179428b368194d318d421509232011&q=${keyword}`, {mode: 'cors'});
    const weatherData = await response.json();
    console.log(weatherData);

    const city = keyword.charAt(0).toUpperCase() + keyword.slice(1);
    cityName.innerText = city;

    showWeather.innerText = weatherData.current.condition.text;
    const weatherImg = document.createElement("img");
    weatherImg.setAttribute("id", "weather-img");
    weatherImg.src = weatherData.current.condition.icon;

    const showTemp = document.createElement("span");
    const showFeelsLike = document.createElement("span");
    showTemp.innerText = weatherData.current.condition.temp_c;
    showFeelsLike.innerText = weatherData.current.condition.feelslike_c;
  
    weatherPic.appendChild(weatherImg);

    
    temperature.appendChild(showTemp);
    feelsLike.appendChild(showFeelsLike);
};

submitBtn.addEventListener("click", getWeather);
<div id="wrapper">

        <header>

            <div id="logo"><img src="images/myweatherapp.png" alt="My Weather App"> 
            <h2>My Weather App</h2></div>
            <div id="search">
                <form>
                    <input type="text" id="keyword" name="search-term" placeholder="City name">
                    <input type="submit" id="submit-button" value=">>">
                </form>
            </div>
        </header>

        <section id="content">
            <div id="content-header">
                <h1>The weather in <span id="city">{Search for your city}</span> today!</h1>
                <div id="weather">
                    <div></div>
                    <h1></h1>
                </div>
            </div>
            <p id="date"></p><p id="time"></p>

            <div id="weather-report">
                <div id="temperature"></div>
                <div id="feels-like"></div>


            </div>

        </section>

    </div>

EDIT: For some reason the icon showed when I pasted it into this code snippet thing but it doesn’t show on browser. The other items still showed as undefined!

For each guild CronJob at diffrent time

How to make cronjobs for every guild at diffrent time?

I’m making my own Discord bot, and I want to make Topic of the Day (something like Question of the Day – QotD). Bot would send message – defined topic to defined channel at defined time (defined by owner or admin) and if time is changed it would change CronJob’s time (via Slash commands), but I can’t solve it.

I was trying to make CronJob to class, so I would write:


client.once(Events.ClientReady, () => {

 guilds.forEach(guild => {

  const TD = new TopicOfTheDay(guild)

  TD.start()

}})

and it didn’t work.

Most efficient way of returning pairs of coordinates in Javascript?

How can I best help Javascript JITs avoid allocation when my functions return one or two coordinate pairs?

e.g.

function getSegment(args) {
    ...
    return [[ax, ay], [bx, by]];
}

or

function getSegment(args) {
    ...
    return [{x: ax, y: ay}, {x: bx, y: by}];
}

or

function getSegment(args) {
    ...
    return [ax, ay, bx, by];
}

or something better.

I’m hoping that a good JIT will see that these values do not live long and so return them on the stack or in registers, rather than making one or three heap allocations. Is this a realistic expectation?

`await` vs `.then()` : order of execution [duplicate]

I’m trying to understand the order of execution of JavaScript promises. In the following code, thenFn() is invoked after awaitFn(), but thenFn() still executes(complete the task) first. Can someone explain why this happens?

const thenPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Resolved!: then');
    }, 200);
});

const awaitPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Resolved!: await');
    }, 200);
});

async function awaitFn() {
    console.log(await awaitPromise);
}

function thenFn() {
    thenPromise.then((res) => console.log(res));
}

awaitFn();
thenFn();

It is noteworthy that, I declare the thenPromise before awaitPromise. If I declare awaitPromise first I get the expected output.

Thanks.

Expected Output:
Resolved!: await
Resolved!: then

Actual Output:
Resolved!: then
Resolved!: await

new FormData(this); not working // this being the inside the callback function when targeting desired form

ejs file to pass form data from a todo.ejs file to a express server file named index.js. What I want is that after submitting it should not go anywhere stay on the same page and reaload to reflect modiifed data with a form.

for that I put some code on client side to send data manually using, new FormData(this), remove the default behavior of form and reload after to reflect the effects.

But it’s not working

here is script.js which is static file included in the todo.ejs file.

document.getElementById("task_form").addEventListener('submit', function(event) {
    event.preventDefault();
    const formData = new FormData(this);
    // for debugging
    // this is printing the data, but not passing to the server.
    var data = {};
    for (let pair of formData.entries()) {
        data[pair[0]] = pair[1];
        console.log(pair[0] + ': ' + pair[1]);
    }
    console.log(data);
    // dubugging ends.

    // Perform the form submission using AJAX/fetch
    fetch('/task', {
        method: 'POST',
        body: formData // Assuming you want to submit form data
    })
    .then(response => {
        if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
        }

        // Handle the redirect by reloading the page
        // window.location.reload(true);
    })
    .catch(error => {
        console.error('Error:', error);
        // Handle errors
    });
});

this is the todo.ejs file form

<!-- enctype="multipart/form-data" content  -->
<form id="task_form" action="/task" method="post">
    <fieldset>
        <legend>Description</legend>
        <input id="task_desc" type="text" name="task" placeholder="define task" value="title">
    </fieldset>
    <fieldset>
        <legend>Duration</legend>
        <label for="start_date">Start : </label>
        <input id="start_date" type="datetime-local" name="start_date"><br>
        <label for="end_date">End : </label>
        <input id="end_date" type="datetime-local" name="end_date"><br>
    </fieldset>
        <input type="submit" value="Add task">
</form>

here is the route thta’s handling data on the sever side.

app.post("/task", (req, res)=>{
  var data = req.body;// this is empty
  console.log(data);// 
  // for debugging
  data.start_date = "2023-11-03T13:44";
  data.end_date = "2023-11-24T13:44";
  var d1 = data["start_date"];
  var d2 = data["end_date"];
  console.log(data);
  if(d1 >= d2) {
    console.log("error d1 >= d2");
    // alert("Add correct date");
  } else{
    data.status = "pending";
    todo.push(data);
    console.log("Correct d1 < d2");
  }

  res.redirect("/todo");
});

I tried to pass the data as an js object using

document.getElementById('task_form').addEventListener('submit', function(event) {
    event.preventDefault();

    const formData = new FormData(this);
    for (let pair of formData.entries()) {
        console.log(pair[0] + ': ' + pair[1]);
    }
});

it’s printing data to the console but not passing data to the server.

I would be extremely grateful please help, thank you!