I am working on GSAP animation but having issues while implementing it with React

I am working on a react project which is having GSAP animation, I have achieved infinite loop animations in with javascript example but not able to implement it in react. when I use some predefined functions it throws a lot of errors check screenshot for reference.Error Screenshot

Here I am providing codepen of javascript which I have achieved and stackbiz where I want to implement it. Your help is appreciated.

https://codepen.io/EmpChirag/pen/bGZNYwo

https://stackblitz.com/edit/gsap-react-basic-f48716-rm5kfn?file=src%2FApp.js

I have tried putting the functions in useEffect, useGsap, useLayoutEffect but I don’t understand how to manage those functions.

I made a to do list in json, but when I call the data in the type script, it gets an error and says to specify the data type

how this fix?
I made a to do list in json, but when I call the data in the type script, it gets an error and says to specify the data type.

pro.json

[
    {
        "id": 234641,
       "const userName": "hamidZareei",
        "email": "[email protected]",
        "password": "34sde2"
    },
    {
        "id": 239760,
        "userName": "amir   ",
        "email": "[email protected]",
        "password": "23sdsd"
    }
]

pro.ts

accountRoutes.get('/account/name/:name', (req, res) => {
  console.log({params: req.params})
  const foundedAcount = getOneAcount({userName: req.params["name"]})
  res.send(foundedAcount)
})

Algorithm to generate a PokeDoku style grid

I’m trying to make my own game based on the 3×3 grid game https://pokedoku.com. Basically, there are a large number of attributes which are applied to the 6 rows and columns of the grid. For each of the intersections of these attributes, you have to choose something that contains both of those attributes.

While making my own version of the game I ran into the issue where I’d get to an attribute and have to backtrack because certain combinations do not exist. Is there a better way to choose the rules than by nesting six loops?

How to define the local variable of for…of loop using property accessor

Saw this short paragraph from MDN JavaScript reference page on for…of statement, at around the end of Description section, it says:

You can use destructuring to assign multiple local variables, or use a property accessor like for (x.y of iterable) to assign the value to an object property.

What does it mean? You can’t have x.y syntax for defining the local variable in a for...of statement.
I tried this verbatimly in a short script file using node. Error message was ReferenceError: x is not defined

What I’d missed?

How to created nested arrays from a nest of arrays?

I’m looking to return an array of objects which contains a sub array of objects.

The data I am extracting from contains an array of ‘projects’ with a bunch of properties and within this array there is an array of ‘work items’. I want to loop/map through the ‘projects’ array and return a new array of objects and within that there will be a ‘subtasks’ property which needs to contain another array of objects which has been developed from the ‘work items’ array within the ‘projects’ array.

Below is where I have got to so far. This is not what I want as I need the main object to just be created when it loops through the projects and then the ‘subtasks’ array to be created when it loops through the ‘work items’. I tried putting the overarching object above the ‘return project.workItems.map….’ line but I was getting syntax errors.

See below this code for an example of the expected output.

  let newProjects1 = projects.map((project, index) => {

  return project.workItems.map((workItem) => {
    return {
      TaskID: index,
      ProjectNo: project.projectNumber,
      TaskName: project.projectTitle,
      StartDate: new Date("11/11/2024"),
      EndDate: new Date(project.projectEnd),
      subtasks: [
        {
          TaskID: index,
          TaskName: workItem.name,
          StartDate: new Date("11/11/2024"),
          Duration: 80,
          Progress: 150,
        },
      ],
    };
  })
;

});

The final output needs to look something like this

  [
{
  TaskID: 1,
  ProjectNo: "29895",
  TaskName: "Stoneybridge WTW",
  StartDate: new Date(projects[0].projectStart),
  EndDate: new Date(projects[0].projectEnd),
  subtasks: [
    {
      TaskID: 1.1,
      TaskName: "Sodium Carbonate",
      StartDate: new Date(projects[0].projectStart),
      Duration: 4,
      Progress: 150,
      comments: "unlucky",
      subtasks: [
        {
          TaskID: 1.11,
          TaskName: "Design",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
        {
          TaskID: 1.12,
          TaskName: "Workshop",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
        {
          TaskID: 1.13,
          TaskName: "Site",
          StartDate: new Date(projects[0].projectStart),
          Duration: 30,
          Progress: 150,
        },
      ],
    },]

This is the input data i.e. the ‘projects’ array, which contains the ‘workItems’ array. This is just one of the objects in the ‘projects’ array

 [{
"projectNumber": 26278,
"projectTitle": "Ifon WTW",
"chemicals": ["sodium hypochlorite", "sodium hydroxide", "pacl"],
"projectStatus": "site survey",
"siteType": "SR",
"location": "Glasgow",
"contractType": "construction",
"designLead": "Craig Garvie",
"projectManager": "Isaac Stanton",
"projectType": "Other",
"spm": "Mark Tench",
"client": "Yorkshire Water",
"comments": "project going swimmingly",
"projectStart": "12/20/2022",
"projectEnd": "07/28/2024",
"createdAt": "2022-11-22T07:43:42Z",
"updatedAt": "2023-04-09T10:13:14Z",
"equipment": [
  { "name": "kiosk", "count": 2 },
  { "name": "tanker fill point", "count": 1 },
  { "name": "dosing skid", "count": 1 },
  { "name": "POA catchpot", "count": 1 },
  { "name": "Low Point Catchpot", "count": 0 },
  { "name": "MCC", "count": 1 }
],
"workItems": [
  {
    "name": "work Item 1",
    "siteSurveyStart": "11/29/2022",
    "siteSurveyEnd": "01/25/2023",
    "designStart": "02/14/2023",
    "designEnd": "03/06/2023",
    "workShopStart": "04/24/2023",
    "workShopEnd": "05/05/2023",
    "rsePremisesStart": "06/24/2023",
    "rsePremisesEnd": "07/09/2023",
    "siteStart": "08/20/2023",
    "siteEnd": "09/13/2023"
  },
  {
    "name": "work Item 2",
    "siteSurveyStart": "11/02/2022",
    "siteSurveyEnd": "01/05/2023",
    "designStart": "02/02/2023",
    "designEnd": "03/24/2023",
    "workShopStart": "04/11/2023",
    "workShopEnd": "05/19/2023",
    "rsePremisesStart": "06/19/2023",
    "rsePremisesEnd": "07/17/2023",
    "siteStart": "08/20/2023",
    "siteEnd": "09/23/2023"
  }
],
"chemical": [{ "name": "sodium carbonate" }, { "name": "sulphuric acid" }],
"projectPersonnel": [
  { "name": "daniel carey" },
  { "name": "erin donnelly" },
  { "name": "craig garvie" },
  { "name": "ryan watson" },
  { "name": "lewis scott" },
  { "name": "jack overfield" },
  { "name": "fidel hernandez" }
]

}]

why node.js backend can’t set cookie to frontend react.js?

i have trouble when i try to send a cookie from node to react for login auth, when i test with insomnia it works with no problem.

this is the result test from insomnia there’s a cookie in connection
Insomnia

this my devtools from chrome, as you guys can see there’s nothing in here
DevTools

// custom config CORS
const configCors = {
    origin : 'http://localhost:3000',
    credentials : true,
    allowedHeaders: ['Content-Type', 'Authorization']
}

// the cookie i want to set
res.cookie("refresh", refresh, {
          httpOnly: true,
          secure: false,
          maxAge: 24 * 60 * 60 * 1000, // in milliseconds
        })

Why cookies don’t exist in devtools react.js, but only exist in insomnia when I test it

for information :
Frontend React.js,
Backend Node.js

how to be creative? what is the answer to create following task [closed]

1.**** Task Form****:
Create a reactive form for adding and editing tasks.
Fields: Task Name, Description, Due Date.

2 Task List Component:
Create a component to display a list of tasks.
Display tasks with their names and due dates.
Include buttons to edit and delete each task.

  1. Chart Component:
    Implement a component for displaying a chart using Apex Charts.
    The chart should visualize the number of tasks due in the next 7 days.

4 Task Service:
Use a service to manage tasks (add, edit, delete, get tasks).
Use dependency injection to inject the service into components.

5 Routing:
Implement routing for the application with two routes:
Route 1: Display the Task List component.
Route 2: Display the Chart component.

6.** Navigation:**
Include a navigation bar with links to switch between the Task List and Chart views.

I have to create 3 different page 1st include form 2nd include list 3rd include chart?
would be great if you reply with codes.

About How to run a certain blockchain project

Hi. I’m new to blockchain and I want to know how to run a certain blockchain project. This is it’s github repository.https://github.com/virajchandra51/MediVault. I have been trying for days for it to run. I would appreciate if someone gave me step by step guid on how to run this.

Currently, Im getting this error.This is the error Im getting. I have changed the address in contact.json but doesnt work. Also, Im getting the following warning when deploying the contract using node deploy.js.

node:51500) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
0xd09eD97239e278d591f80Eb45437895aa201F451

I have connected ganache to metamask using import accounts. I would appreciate if you gave me any sort of help here…

Error validating generated transaction: Error running script for input 0 referencing at 0: Script was NOT verified successfully

Good afternoon, please help me figure out the error, I can’t understand why the transaction doesn’t go through.
Here is my code:

const express = require('express');
const app = express();
const port = 3000;
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const axios = require('axios');
var bitcoin = require("bitcoinjs-lib");
var secp = require('tiny-secp256k1');
var ecfacory = require('ecpair');
var ECPair = ecfacory.ECPairFactory(secp);
app.use(cors());


app.post('/submit', (req, res) => {
    const senderAddress = 'mxqxyFpBSxXHaL928G98tuL5pwX1gpmgTJ';
    const senderPrivateKey = "cQg2X7cVEBSHWW3mUdXm3VPAArRJc3K9PUNkmaEsHYFdKNN29CDt";
    const { recipientAddress , amountToSend } = req.body;
    const keyBuffer = Buffer.from(senderPrivateKey);
    const totalLength = 32;
    const result = Buffer.concat([keyBuffer], totalLength);
    var keys = ECPair.fromPrivateKey(result);
    const apiUrl = "https://api.blockcypher.com/v1/btc/test3/";
    const newtx = {
        inputs: [{addresses: [senderAddress]}],
        outputs: [{addresses: [recipientAddress], value: (parseInt(amountToSend  * 100000000))}]
    };
    axios.post(apiUrl+'txs/new', newtx)
      .then(function(response) {
        const tmptx = response.data;
        tmptx.pubkeys = [];
        tmptx.signatures = tmptx.tosign.map(function (tosign, n) {
          tmptx.pubkeys.push(keys.publicKey.toString('hex'));
          return bitcoin.script.signature.encode(
            keys.sign(Buffer.from(tosign, "hex")),
            0x01,
          ).toString("hex").slice(0, -2);
        });
        axios.post(apiUrl + 'txs/send', tmptx)
          .then(function (finaltx) {
            res.status(200).send('Транзакция отправлена!: ' + finaltx.data);
          })
          .catch(function (error) {
            res.status(500).send('Ошибка при отправке транзакции 1:' + (error.response ? error.response.data : error.message));
            console.error('Ошибка при отправке транзакции 1.1:', error.response ? error.response.data : error.message);
          });
      })
      .catch(function (error) {
          res.status(500).send('Ошибка при создании транзакции 2.1:' + (error.response ? error.response.data : error.message));
          console.error('Ошибка при создании транзакции 2.2:', error.response ? error.response.data : error.message);
       });
});
app.listen(port, () => {
console.log(`Сервер запущен на порте ${port}`);
});

Error validating generated transaction: Error running script for input 0 referencing efc9c6122a60b1aa78805686dd656a38708334f715d197e559a110c36655cdfc at 0: Script was NOT verified successfully.
[enter image description here](https://i.stack.imgur.com/mTNtE.jpg)

How to catch ERR_INTERNET_DISCONNECTED, ERR_NETWORK_CHANGED, etc?

TL;DR – I want to be able to programmatically reload the page so as to gracefully recover from an ERR_INTERNET_DISCONNECTED error, rather than leaving the user with a half-loaded, dead page which cannot be recovered and must be reloaded when the network reconnects.

I am listening for the ‘offline’ and ‘online’ events and I can catch those and handle them, however I want to be able to catch and handle ERR_INTERNET_DISCONNECTED and other such errors that occur when the connection is dropped while javascript is loading modules. Why? Because I want to be able to handle the following two conditions:

  1. The page has already fully loaded and the javascript is sitting idle, waiting for input. If the network disconnects and reconnects during this time, it doesn’t matter – the js will function just fine after the internet has reconnected.

  2. The page is in the middle of loading when the network disconnects. This is a non-recoverable error and requires that the page be re-loaded.

‘offline’ and ‘online’ events are dispatched in both cases, but it is only in case 2 that ERR_INTERNET_DISCONNECTED (etc) errors are thrown. So I want to be able to distinguish between the two cases and, when the network disconnection results in a non-recoverable error, display a modal to the user saying something along the lines of “The network has disconnected and the page is trashed, it will be reloaded when the network reconnects.” (or whatever). But to do that I need to be able to catch ERR_INTERNET_DISCONNECTED. I have tried using the general error listeners window.addEventListener('error', () => { ... }) and window.onerror = (a, b, c, d, e) => { ... } but it seems the ERR_INTERNET_DISCONNECTED cannot be caught by these. Is there any way to check programmatically to see if one of these errors has been thrown?

Of course, any code that is intended to catch and gracefully recover from ERR_INTERNET_DISCONNECTED could itself not be fully loaded when the error occurs, but I should at least try to gracefully recover from the error!

window.addEventListener('error', () => { ... }) and window.onerror = (a, b, c, d, e) => { ... }. No dice.

Error: Cannot find module ‘moment’ in the render deployin nodejs server file

solve this problem and run npm i moment i in the place of npm i or npm install
Error Encountered:

While deploying a Node.js server on Render, you’re encountering the error “Cannot find module ‘moment’.” This indicates that the moment module, used for date and time manipulation, is either not installed or not accessible within the deployment environment.

Resolving the Issue:

  1. Install moment:

    • Access the terminal within your project’s root directory.
    • Execute the following command to install moment locally:
      npm i moment
      

      This ensures the module is included in your project’s dependencies.

  2. Verify Installation:

    • Check if moment is now listed under “dependencies” in your package.json file.
    • Confirm its presence within the node_modules folder.
  3. Deployment Considerations:

    • Render’s build process might not automatically include node_modules.
    • To ensure moment is available during deployment, run npm i moment i.
      This flag typically includes devDependencies for deployment.

Additional Troubleshooting Steps:

  • Typos: Double-check for any typos in the require statement importing moment.
  • Cache Clearing: If the issue persists, clear the npm cache using npm cache clean --force and reinstall moment.
  • Development Server: Restart your development server to reload dependencies.
  • Module Location: If moment is installed in a non-standard location, provide the correct path in the require statement.
  • Version Compatibility: Ensure moment is compatible with your Node.js version.

Request for Further Information:

For more tailored assistance, please provide the following:

  • Relevant code snippet from index.js
  • Your project structure
  • Any additional error messages or logs

Remember:

  • Avoid global installations of moment to prevent version conflicts.
  • If you have any further questions or require additional guidance, feel free to ask!

How to update Data in every 10 sec in ajax?

I’m currently facing an issue with the setInterval function in my JavaScript code. I’m trying to use it to update a card’s content every few seconds, but instead of updating the existing card, it seems to be creating multiple copies.

function Hide(HideID) {
  HideID.style.display = "none";
}

$(document).ready(function() {
      fetchData();

      function fetchData() {
        const apiUrl = `https://api.cricapi.com/v1/cricScore?apikey=key`;
        $.ajax({
          url: apiUrl,
          type: "GET",
          success: function(data) {
            globalData = data
            UpdateData(data)
          },


          error: function(data) {
            console.log("error");
            console.log(data);
          }
        });

      }

      function UpdateData(data) {


        data.data.sort((a, b) => {
          const order = {
            live: 1,
            fixture: 2,
            result: 3
          };
          return order[a.ms] - order[b.ms];
        });

        console.log(data.data[0], 'yes?')

        var htmlContent = ''; // Create an empty string to store HTML content
        for (var i = 0; i < data.data.length; i++) {
          htmlContent += `<div class="ritekhed-fixture-table-slider-layer">
                <time class="ritekhed-slider-head" datetime="" style="height:64px;text-align:center;">${data.data[i].matchType.toUpperCase()}</time>
                <ul class="ritekhed-bgcolor">
                 <li class="ritekhed-fixture-addtext"> ${data.data[i].dateTimeGMT.split('T')[0]} </li>
                <li class="ritekhed-fixture-vs">
                <span style="float:left;"><img src="${data.data[i].t1img}" class="img-responsive" style="width:35px; height:35px" /><br /><strong>${data.data[i].t1.split(' ').slice(-1)[0]}</strong></span>
                <div id=""  class="counter_small" ><span >VS</span></div>
                <span><img src="${data.data[i].t2img}" class="img-responsive" style="width:35px; height:35px" /><br /><strong>${data.data[i].t2.split(' ').slice(-1)[0]}</strong></span>
                <br />
                <div style="margin-top:2%;text-align:center !important;"></div>
                </li>
                <li class="ritekhed-fixture-vs" style="height: 84px; ">                <span style="text-align: right; display: inline-block; width: 50%;">${data.data[i].t2s}</span>
<span style="text-align: left; display: inline-block; width: 50%;">${data.data[i].t1s}</span>
        <br><strong style="float: none; position: relative;top:8px">${data.data[i].status}</strong> </li>
                <li class="ritekhed-fixture-addtext" style="background-color:black;"><a href="" style="color:#51e829;">Telegram Link</a></li>
                </ul>
                </div>`;
        }
        // Append the generated HTML content to the slider
        $('#sl33').append(htmlContent);

And I’m using slick-slider so after every 10 sec, the slider is also not working properly

$('#sl33').slick({
  dots: false,
  infinite: true,
  prevArrow: "<span class='slick-arrow-left'><i class='fa fa-chevron-left'></i></span>",
  nextArrow: "<span class='slick-arrow-right'><i class='fa fa-chevron-right'></i></span>",
  speed: 2000,
  autoplay: false,
  fade: false,
  autoplaySpeed: 3000,
  slidesToShow: 5,
  slidesToScroll: 5,
  responsive: [{
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 1,
        infinite: true,
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 1
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]
});

Set default values in react-hook-form conditionally

Background:
I have a very long complex form with deep nested objects creating using rhf (react-hook-form). I want to provide a checkbox at the top of the form which toggles the default values in the fields to assist the user.

Problem
By using rhf, I was able to fill up the defaultValues using reset method but now the issue is once I call the reset method with the defaultValues, I can’t unset the values using the reset if I provide an empty object.

Things I’ve tried
I’ve tried using the setValue method but it unset only 1 field at once and it’ll require recursion to set values for deep-nested object.

Code
Here’s a very minimal example of what I’m trying to do.

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

const defaultValues = { name: `John Doe` };

const Form = () => {
  const [useDefaultValues, setUseDefaultValues] = useState(false);
  const { register, handleSubmit, reset } = useForm();

  useEffect(() => {
    if (useDefaultValues) {
      reset(defaultValues);
    } else {
      reset({}, { keepValues: false, keepDefaultValues: false });
    }
  }, [useDefaultValues]);

  return (
    <>
      <label>
        <input
          type="checkbox"
          value={useDefaultValues}
          onChange={() => setUseDefaultValues((prev) => !prev)}
        />
        Use Default values
      </label>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name</label>
          <input type="text" name="name" {...register("name")} />
        </div>
        <input type="submit" />
      </form>
    </>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Form />, rootElement);

Codesandbox: https://codesandbox.io/p/sandbox/react-hook-form-reset-form-forked-sxmy8q?file=%2Fsrc%2Findex.js%3A1%2C1-42%2C1

Notice how unsetting the defaultValues doesn’t empty the form again

error shows [object Object] with multer and cloudinary upload

I’ve been trying to create an api route that accepts multiple images for carouselImages and single photo for other three atrributes(photo, leftPic, rightPic). However I’m getting [object Object] in the console. The images aren’t getting uploaded to cloudinary too.

what am I doing wrong in my code?

backend route file

import express from "express";
import { createGame } from "../controllers/game.js";
import { checkAdminOrModerator } from "../middlewares/auth.js";
import { v2 as cloudinary } from 'cloudinary';
import multer from 'multer';
import 'dotenv/config';
import { CloudinaryStorage } from 'multer-storage-cloudinary';

const gameRouter = express.Router();

cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.CLOUDINARY_KEY,
    api_secret: process.env.CLOUDINARY_SECRET
});

const storage = new CloudinaryStorage({
    cloudinary,
    params: {
        folder: 'Demo',
        allowedFormats: ['jpeg', 'png', 'jpg', 'webp'],
    }
});

const upload = multer({
    storage,
});

gameRouter.post("/addGame", upload.fields([
    { name: 'photo', maxCount: 1 },
    { name: 'leftPic', maxCount: 1 },
    { name: 'rightPic', maxCount: 1 },
    { name: 'carouselImages', maxCount: 3 }
]), checkAdminOrModerator, createGame)

export default gameRouter

controller file

import Game from "../model/Game.js";

export async function createGame(req, res) {
    console.log('req.body', JSON.stringify(req.body, null, 2)) // this doesn't get logged on console
    console.log('req.files', JSON.stringify(req.files, null, 2)) //I guess I'm getting [object Object] from here but 'req.files' doesn't show up in the console either
    try {
        const {
            name,
        } = req.body;

        const photo = req.files['photo'] ? req.files['photo'][0].path : '';
        const leftPic = req.files['leftPic'] ? req.files['leftPic'][0].path : '';
        const rightPic = req.files['rightPic'] ? req.files['rightPic'][0].path : '';
        const carouselImages = req.files['carouselImages']
            ? req.files['carouselImages'].map((image) => image.path)
            : [];

        const newGame = new Game({
            name,
            photo,
            leftPic,
            rightPic,
            carouselImages
        });

        const savedGame = await newGame.save();

        return res.status(201).json(savedGame);
    } catch (error) {
        console.log('error', error)
        return res.status(500).json({ error: 'Internal server error' });
    }
}

frontend code. using vue2 and bootstrap vue

<template>
  <div class="wrapper">
    <b-form @submit.prevent="saveGame">
      <b-form-group label="Name">
        <b-form-input v-model="formData.name" />
      </b-form-group>
      <b-form-group label="Route Name">
        <b-form-input v-model="formData.routeName" />
      </b-form-group>
      <b-form-group label="Photo">
        <b-form-file @change="handlePhotoFileChange" />
      </b-form-group>
      <b-form-group label="Left Pic">
        <b-form-file v-model="leftPicFile" />
      </b-form-group>
      <b-form-group label="Right Pic">
        <b-form-file v-model="rightPicFile" />
      </b-form-group>

      <!-- Carousel Images -->
      <b-form-group label="Carousel Images">
        <b-form-file
          v-for="(carouselImage, index) in carouselImages"
          :key="index"
          @change="handleCarouselImageChange(index, $event)"
        />
        <b-button @click="addCarouselImage" variant="success"
          >Add Image</b-button
        >
      </b-form-group>
      <!-- Save and cancel buttons -->
      <b-button type="submit" variant="primary">Save</b-button>
    </b-form>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      formData: {
      },
      photoFile: null,
      leftPicFile: null,
      rightPicFile: null,
      carouselImages: [],
    };
  },
  methods: {
    addCarouselImage() {
      this.carouselImages.push(null);
    },

    removeCarouselImage(index) {
      this.carouselImages.splice(index, 1);
    },

    handlePhotoFileChange(event) {
      if (event.target.files && event.target.files.length > 0) {
        this.photoFile = event.target.files[0];
      }
    },

    handleCarouselImageChange(index, event) {
      this.$set(this.carouselImages, index, event.target.files[0]);
      console.log("carouselImages", this.carouselImages)
    },
    async saveGame() {
      const token = localStorage.getItem("token");
      if (!token) {
        console.error("Token not found");
        return;
      }

      const formData = new FormData();
      formData.append("name", this.formData.name);

      if (this.photoFile) {
         formData.append("photo", this.photoFile);
      }
      if (this.leftPicFile) {
         formData.append("leftPic", this.leftPicFile);
      }
      if (this.rightPicFile) {
         formData.append("rightPic", this.rightPicFile);
      }
      this.carouselImages.forEach((file) => {
         if (file) {
             formData.append('carouselImages', file);
         }
      });
      for (let [key, value] of formData.entries()) {
         console.log(key, value);
        }
      const url = `${process.env.VUE_APP_API_ENDPOINT}/game/addGame`;
      try {
        const response = await axios.post(url, formData, {
          headers: {
            Authorization: token,
          },
        });

        if (response.status === 200) {
          console.log("Game saved successfully");
        } else {
          console.error("Error saving game");
        }
      } catch (error) {
        if (error.response && error.response.status === 401) {
          console.error("Token expired or invalid");
          this.$router.push("/login");
        }
        console.error("Error saving game:", error);
      }
    },
  },
};
</script>

backend index.js

import express from "express";
import mongoose from "mongoose";
import 'dotenv/config';
import cors from 'cors';

import gameRouter from "./routes/game.js";

const app = express();

app.use(cors())
app.use(express.json());

app.use("/game", gameRouter);
app.use("/", (req, res) => {
  res.send("Hello World");
});

mongoose
  .connect(
    process.env.MONGODB_URI
  )
  .then(() => app.listen(3000))
  .then(() => console.log("Connected to database"))
  .catch((err) => console.log(err));