Please help me to resolve this error in my code

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (node:_http_outgoing:652:11)
at ServerResponse.header (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibresponse.js:795:10)
at ServerResponse.contentType (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibresponse.js:625:15)
at ServerResponse.send (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibresponse.js:150:14)
at done (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibresponse.js:1053:10)
at tryHandleCache (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesejslibejs.js:280:5)
at exports.renderFile [as engine] (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesejslibejs.js:491:10)
at View.render (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibview.js:135:8)
at tryRender (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibapplication.js:657:10)
at Function.render (C:UserskamblOneDriveDesktopApnaCollegemYSQLnode_modulesexpresslibapplication.js:609:3)

I am currently learning so haven’t been able to resolve this error
This is my code:

const { faker } = require('@faker-js/faker');
const mysql=require("mysql2");
const express= require( "express" );
const app=express();
const path=require("path");

app.set( 'view engine', 'ejs' );
app.set("views",path.join(__dirname,"/views"));

const connection=mysql.createConnection({
    host:"localhost",
    user:"root",
    database:"delta_app",
    password:"Arbitron12#7006"
});

let getRandomUser=()=>{
    return [
            faker.string.uuid(),
            faker.internet.userName(),
            faker.internet.email(),
            faker.internet.password()
        ];
    };
//Home route
app.get("/",(req,res)=>{
    let q=`SELECT count(*) FROM temp`
    try{
    connection.query(q,(err,result)=>{
        if(err) throw err;
        let count=result[0]["count(*)"]
        res.render("Home.ejs",{count})
    });
    } catch (err){
    console.log(err);
    res.send("Some error in DB")
    }
});

//Show route
app.get("/user",(req,res)=>{
    let q= `select * from temp`;
    try{
        connection.query(q,(err,users)=>{
            if(err)throw err;
            res.render("showusers.ejs",{ users });
        });
        } catch (err){
        console.log(err);
        res.send("Some error in DB");
        }
    res.send("success");
});
app.listen("8080",() => {
    console.log("Server is listening to the port 8080");
});

why date is rest to todays date?

I am using below plugin
https://www.npmjs.com/package/react-datepicker
documentation
https://reactdatepicker.com/#example-date-range-for-one-datepicker-with-disabled-dates-highlighted

I disable pass date in my demo application . But when I enter past date it change to “today’s” date why ?

step to reproduce function

  1. change year 2024 to 2022 by typing .. it again back to 2024 ..why ? it should show error

here is my code

https://codesandbox.io/p/sandbox/react-datepicker-example-forked-y7rs95?file=%2Fsrc%2Findex.tsx%3A3%2C25-3%2C41

function App() {
  const [startDate, setDate] = React.useState(new Date());
  const today = new Date();

  const selectDateHandler = (d) => {
    setDate(d);
  };
  const disabledDate = (date) => {
    const currentDate = new Date();
    const selectedDate = new Date(date);
    return currentDate.getTime() < selectedDate.getTime();
  };

  return (
    <div className="App">
      <DatePicker
        dateFormat="yyyy/MM/dd"
        selected={startDate}
        onChange={selectDateHandler}
        filterDate={disabledDate}
        todayButton={"Today"}
      />
    </div>
  );
}

Problem with Google Cloud Function Downloading Stored Images

I am trying to use a google cloud function to download 100-1000s of images that I have stored in google firebase storage. I initially did this operation client-side, however am now having to take a server side approach due to memory issues and user experience in the front end.

Here is the cloud function I have currently deployed:


//deployed cloud function

const functions = require('firebase-functions');
const fetch = require('node-fetch');
const archiver = require('archiver');
const fs = require('fs');
const path = require('path');
const os = require('os');
const admin = require('firebase-admin');

admin.initializeApp({
 credential: admin.credential.applicationDefault(),
 storageBucket: process.env.FIREBASE_STORAGE_BUCKET
});

const runtimeOpts = {
 timeoutSeconds: 300, 
 memory: '8GB' 
};

exports.batchDownload = functions
 .runWith(runtimeOpts)
 .https.onRequest(async (req, res) => {
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', 'POST');
    res.set('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
      res.status(204).send('');
      return;
    }

    const imageUrls = req.body.imageUrls;

    if (!Array.isArray(imageUrls)) {
      res.status(400).send('Invalid request: incorrect data format');
      return;
    }

    const tempDir = path.join(os.tmpdir(), 'images');
    const zipPath = path.join(os.tmpdir(), 'images.zip');

    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir);
    }

    const downloadPromises = imageUrls.map(async (url, index) => {
      try {
        const response = await fetch(url);
        const buffer = await response.buffer();
        const filePath = path.join(tempDir, `image${index}.jpg`);
        fs.writeFileSync(filePath, buffer);
      } catch (error) {
        console.error(`Failed to download image at ${url}:`, error);
        res.status(500).send(`Failed to download image at ${url}`);
        return;
      }
    });

    await Promise.all(downloadPromises);

    const output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', {
      zlib: { level: 9 }, 
    });

    archive.directory(tempDir, false);
    archive.pipe(output);

    await archive.finalize();

    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', 'attachment; filename=images.zip');
    const stream = fs.createReadStream(zipPath);
    stream.pipe(res);
    res.end();

    fs.rmdirSync(tempDir, { recursive: true });
    fs.unlinkSync(zipPath);
 });

I have ensured that the dependencies were all correctly installed prior to deployment:


//cloud function package.json
{
  "name": "batchDownload",
  "version": "0.0.1",
  "dependencies": {
      "firebase-functions": "^3.16.0",
      "firebase-admin": "^10.0.0",
      "node-fetch": "^2.6.1",
      "archiver": "^5.3.0",
      "fs": "^0.0.2",
      "path": "^0.12.7",
      "cors": "^2.8.5"
   }
}

When i try to call the function from the front end and pass hundreds of download firebase urls to the function i get:

[id].tsx:262 Error initiating image download: Error: Failed to initiate image

and POST HIDDEN URL 400 (Bad Request)

I initially had CORS errors, but solved them but setting CORS settings for my storage bucket.

Here is my async front end function:

  const downloadAllImages = async () => {
    if (imagesToDownload.length < 1) {
       return;
    }
   
    const imageDownloadURLs = imagesToDownload.map(image => image.downloadURL);
   
    try {
       const response = await fetch(STORAGE_BUCKET_URL, {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json',
         },
         body: JSON.stringify({ imageDownloadURLs }),
       });
   
       if (!response.ok) {
         throw new Error(`Failed to initiate image download: ${response.statusText}`);
       }
   
       const blob = await response.blob();
       const url = window.URL.createObjectURL(blob);
       const a = document.createElement('a');
       a.href = url;
       a.download = 'images.zip';
       a.click();
   
       setShowDownloadAllImagesModal(false);
       setIsDownloading(false);
   
    } catch (error) {
       console.error(`Error initiating image download: ${error}`);
       setShowDownloadAllImagesModal(false);
       setIsDownloading(false);
    }
  };

I am using react.js at front end and imageDownURLs is an array of hundreds of the download url strings, the data looks okay front end but im not sure if there is a problem when it reaches the function?

Is anyone able to point out where I could be going wrong please? I have tried playing around with the function and different ways of writing it and trying both gen 1 and 2 (currently gen 1) and still got getting further forward.

in the firebase cloud functions logs i can see:

Function execution started
Function execution took 5 ms, finished with status code: 204
Function execution started
Function execution took 5 ms, finished with status code: 400

I have added my projects env variables into the function in google cloud console.

Thanks for any insight! 🙂

How to print on client side using javascript?

I am using a JSON object data fetch from backend and the data structure is similar to below code.

{
"Id":"SP120020222",
"Name": "John Doe",
"Age": 22,
"Address": "ST02220, B. Constext, M. City Mate",
"CompanyInfo": {
    "Id": "udise-ekjdl-2233",
    "Name": "Company",
    "Logo": "company-logo.png",
    "Profile": "company-profile.png"
}
}

I now render this code into a html page and then print it with an exactly paper size (228mm x 379mm). I am using simple js like window.print() as below code snippet.

 <script>
  function printing() {
    window.onbeforeprint = function() {
       console.log('User clicked on Print button');
    };

    window.onafterprint = function() {
       console.log('User clicked on Cancel button');
    };

    window.print({silent: true});
}
</script>

I think, there is a way to send content directly to the printer without using window.print() function but I have no idea. Thus, I use window.print() function but I have some questions.

The questions are:

 1. How can I detect user clicked on CANCLE/PRINT/SAVE button?

 2. How to detect prints success/fail, if user clicked on PRINT?

 3. Or there is any better way to print html code without using window.print() function?

I am junior programmer and first time create project with print report. I urgent to kick-off the project if this issue is gone.

Thank you in advance.

Why doesn’t parseFloat() fix NaN (Javascript)?

This code produces NaN errors where there should be numerical output:
myArray = myFunction(x[0],x[1],x[2]);
So I changed it to
myArray = myFunction(parseFloat(x[0]),parseFloat(x[1]),parseFloat(x[2]));
with no effect on the output.

I wrote an alert before this line to see which parameter was the problem:

alert(isNan(x[0])+isNaN(x[1])+isNaN(x[2]));
myArray = myFunction(parseFloat(x[0]),parseFloat(x[1]),parseFloat(x[2]));

which gave me an alert saying “falsefalsefalse”.
The function which generates the array I’m here calling x[] reads

function sortXYZ (x,y,z,orderKey) {
    switch(orderKey) {
        case "abc" : return [x,y,z]; break;
        case "acb" : return [x,z,y]; break;
        case "bac" : return [y,x,z]; break;
        case "bca" : return [y,z,x]; break;
        case "cab" : return [z,x,y]; break;
        case "bgr" : return [z,y,x]; break;
    }
}

So I changed it to

function sortXYZ (x,y,z,orderKey) {
    alert(isNaN(x)+""+isNaN(y)+""+isNaN(z));
    switch(orderKey) {
        case "abc" : return [parseFloat(x),parseFloat(y),parseFloat(z)]; break;
        case "acb" : return [parseFloat(x),parseFloat(z),parseFloat(y)]; break;
        case "bac" : return [parseFloat(y),parseFloat(x),parseFloat(z)]; break;
        case "bca" : return [parseFloat(y),parseFloat(z),parseFloat(x)]; break;
        case "cab" : return [parseFloat(z),parseFloat(x),parseFloat(y)]; break;
        case "cba" : return [parseFloat(z),parseFloat(y),parseFloat(x)]; break;
    }
}

which gives me another alert saying “falsefalsefalse”, and still outputs NaN instead of numbers.

Not all the outputs that ought to be numerical have turned into NaN, just some of them; I have yet to find any rhyme or reason as to which ones.

What do I do?

The time from my google spreadsheet is being displayed wrongly in the sheet’s web app, users see 1899 as year instead of just the time

I have this function that automatically assigns the time when cells are being filled up in certain rows. It works fine in the datasheet, but in the web app that I created for this sheet, VERY wrong dates are being displayed. The time is being read as December 30, 1899.

Here’s the code:

function onEdit(e) {
  var sheet = e.source.getActiveSheet();
  var range = e.range;
  var column = range.getColumn();
  
     // Check if the edited cell is in column 2 (B), 5 (E), or 8 (H)
  if (column == 2 && sheet.getName() == "Join Queue [FOR ADVISEES]") { // Column 2
    var row = range.getRow();
    var dateCell = sheet.getRange(row, 1);
    if (dateCell.getValue() === "") {
      dateCell.setValue(new Date());
    }
      sheet.getRange(blankRow, 7).setValue(Session.getActiveUser().getEmail());

  } else if (column == 6 && sheet.getName() == "Join Queue [FOR ADVISEES]") { // Column 6
    var row = range.getRow();
    var timeCell = sheet.getRange(row, 9);
    if (timeCell.getValue() === "") {
      var currentTime = new Date();
      var formattedTime = Utilities.formatDate(currentTime, Session.getScriptTimeZone(), "HH:mm:ss");
      timeCell.setValue(formattedTime);
    }
  } else if (column == 8 && sheet.getName() == "Join Queue [FOR ADVISEES]") { // Column 8
    var row = range.getRow();
    var timeCell = sheet.getRange(row, 10);
    if (timeCell.getValue() === "") {
      var currentTime = new Date();
      var formattedTime = Utilities.formatDate(currentTime, Session.getScriptTimeZone(), "HH:mm:ss");
      timeCell.setValue(formattedTime);
    }
  }
}

And here’s how they are being shown in the web app (these are from the two else if statements btw):

enter image description here

Now, I noticed that the code in the main if statement is giving the correct date and time, here: so I tried to use the same code as that, and use that to the remaining columns.so the code became:

function onEdit(e) {
  var sheet = e.source.getActiveSheet();
  var range = e.range;
  var column = range.getColumn();
  
  // Check if the edited cell is in column 2 (B), 5 (E), or 8 (H)
  if (sheet.getName() == "Join Queue [FOR ADVISEES]" && [2, 6, 8].includes(column)) {
    var row = range.getRow();
    var dateCell;
    
    if (column == 2) { // Column 2
      dateCell = sheet.getRange(row, 1);
      if (dateCell.getValue() === "") {
        dateCell.setValue(new Date());
      }
      sheet.getRange(row, 7).setValue(Session.getActiveUser().getEmail());
    } else if (column == 6) { // Column 6
      dateCell = sheet.getRange(row, 9);
      if (dateCell.getValue() === "") {
        dateCell.setValue(new Date()); // Set current date and time
      }
    } else if (column == 8) { // Column 8
      var statusCell = sheet.getRange(row, 8);
      if (statusCell.getValue() === "DONE") {
        dateCell = sheet.getRange(row, 10);
        if (dateCell.getValue() === "") {
          dateCell.setValue(new Date()); // Set current date and time
        }
      }
    }
  }
}

however, it did not came out like the first one, and only the year has changed. From 1899, it’s now giving 1970.

why bootstrap tour not working correctly?

hi I want user bootstrap tour in my project to create some help. I write the code just like the sample. but the code not worked correctly.
in other word as soon as my page load the first step is show even without click the help button. also the back, next and end button not shows. like this image:

enter image description here

also I get this error in my console:

Uncaught TypeError: Cannot read properties of undefined (reading
‘getTipElement’)
at o._showPopover (bootstrap-tour.min.js:22:12052)
at o._showPopoverAndOverlay (bootstrap-tour.min.js:22:11093)
at o._showPopoverAndOverlay (bootstrap-tour.min.js:22:51)
at HTMLBodyElement. (bootstrap-tour.min.js:22:13449)
at r.complete (jquery.min.js:2:62910)
at c (jquery.min.js:2:28327)
at Object.fireWith [as resolveWith] (jquery.min.js:2:29072)
at u (jquery.min.js:2:59642)
at S.fx.tick (jquery.min.js:2:64608)
at ot (jquery.min.js:2:58967)

I use the bootstrap 5.3.2 version.
this is my button code:

<button id="SiteTour" type="button" class="btn btn-light btn-floating btn-lg border-success position-fixed rounded-circle hvr hvr-grow"
        style="bottom: 70px; right: 20px; z-index:1000;" data-SiteTour>
 help
</button>

and this is my JavaScript sample code:

<script>
    // Instance the tour
    var tour = new Tour({
        steps: [
            {
                element: "#sectionText",
                title: "Title of my step",
                content: "Content of my step"
            },
            {
                element: "#MainBody",
                title: "Title of my step",
                content: "Content of my step"
            }
        ]
    });

    // Initialize the tour
    tour.init();

    // Start the tour
    tour.start();
</script>

how can fix this? please help.

Create office “news” displayboard?

Looking to have a list of say 5-10 websites which are all news based and often update with very interesting news articles every 15-20 minutes.

I want to create a small script which can have a pool of 3 websites which will automatically refresh every 30 seconds and basically ‘rotate through’ the list of sites. My only issue is I want to strip down the website so it hides the ‘header’ and ‘menu’ HTML when the page renders and that way you are left only with the breaking news article.

Also, would like to include facebook pages (but only the most recent post, so hide the header banner image, etc.

Is this possible?

I’ve tried this but it blocks the websites I want… (does not support frames)… also, how would I strip code (headers, etc.)

<!doctype html>
<html>
<style>
html,body,iframe{height:100%;width:100%;border:0;padding:0;margin:0;}
html,body{overflow:hidden;}
</style>
<iframe></iframe>
<script>
var timer = 5;
var sites = [
    'http://www.bing.com/',
    'http://www.ask.com/',
    'https://duckduckgo.com/'
];
var frame = document.getElementsByTagName("IFRAME")[0];
var index = 0;
var cycle = function() {
    frame.src = sites[index];
    if(++index>=sites.length) {
        index = 0;
    }
    setTimeout(cycle,timer*1000);
}
cycle();
</script>
</html>

State is undefined after button click [duplicate]

I’m trying to play a bit with react native. I got an existing loging form and then I want to integrate it with a local API.

I’m doing a simple api call on button click, but my username/password state always comes in as undefined.

Can anyone help me figure out what’s the issue?

Code bellow:

import React, { useState } from 'react'
import { Alert, Button, Image, Pressable, SafeAreaView, StyleSheet, Switch, Text, TextInput, View } from 'react-native'
import baseURL from './ApiUtils';

const logo = require("./assets/icon.png")

export default function LoginForm() {
const [click, setClick] = useState(false);
const { username, setUsername } = useState("");
const { password, setPassword } = useState("");
const Login = data => {
    console.log(username); // comming in as undefined
    console.log(password); // comming in as undefined
    return baseURL
        .post('login', {
            username: username,
            password: password
        })
        .then(
            response => {
                console.log(response);
                console.log(response.data);
                return response.data;
            },
            error => {
                console.log('postAnswer error: ' + error);
            },
        );
};

return (
    <SafeAreaView style={styles.container}>

        <Image source={logo} style={styles.image} resizeMode='contain' />
        <Text style={styles.title}>Login</Text>
        <View style={styles.inputView}>
            <TextInput style={styles.input} placeholder='EMAIL OR USERNAME' value={username} onChangeText={setUsername} autoCorrect={false}
                autoCapitalize='none' />
            <TextInput style={styles.input} placeholder='PASSWORD' secureTextEntry value={password} onChangeText={setPassword} autoCorrect={false}
                autoCapitalize='none' />
        </View>
        <View style={styles.rememberView}>
            <View style={styles.switch}>
                <Switch value={click} onValueChange={setClick} trackColor={{ true: "green", false: "gray" }} />
                <Text style={styles.rememberText}>Remember Me</Text>
            </View>
        </View>

        <View style={styles.buttonView}>
            <Pressable onPress={Login}>
                <Text >LOGIN</Text>
            </Pressable>

        </View>

    </SafeAreaView>
)
}

Text size not changing for h1 and h2 elements in Tiptap editor

I’m using Tiptap for a rich text editor. I have h1 and h2 heading elements, but when I change the text to these headings, the font size doesn’t visually change. Inspecting the element in the browser confirms the tag is correctly set to h1 or h2, but the size remains the same as regular text.

I’ve downloaded and configured all the necessary Tiptap extensions, but there’s no apparent font size change for headings. While inspecting the element, it shows up as h1 or h2 as expected.

What I’ve tried:

Used h1 and h2 elements in Tiptap editor.
Inspected the element in the browser to verify tag changes.
Downloaded and configured all Tiptap extensions.

<div className="w-4/5 mx-auto h-100 border-4 rounded-3xl">
                    <div className="rounded-3xl m-5">
                        <h1 className="text-center font-extrabold text-3xl">
                            Create Blog
                        </h1>
                        <form className="space-y-4 md:space-y-6 w-4/5 mx-auto h-100" action="#" >
                            
                            <div>
                                
                                <Tiptap content={content} 
                                onChange = {(newcontent:string) => handleChange1(newcontent)}/>
                            </div>
                        </form>
                    </div>
                </div>
                
                

Tiptap Configurtion

const Tiptap = ({ content, onChange }: any) => {

    const handleChange1 = (newContent: string) => {
        onChange(newContent)
    }
    const editor = useEditor({
        extensions: [
            Document,
            Paragraph,
            Text,
            Heading.configure({
                levels: [1, 2],
            }),
            CodeBlockLowlight.configure({
                lowlight,
            }),
            StarterKit.configure({
                bulletList: {
                    HTMLAttributes: {
                        class: "bullet_class",
                    },
                },
                orderedList: {
                    HTMLAttributes: {
                        class: "order_class",
                    },
                },
                heading: {
                    HTMLAttributes: {
                        class: ``,
                    },
                },
            }),
            Image,
            BulletList.configure({
                HTMLAttributes: {
                    class: 'list-disc pl-13'
                }
            }),
            ListItem,
            Underline,
            Link.configure({
                openOnClick: false,
                autolink: true,
            }),
            OrderedList.configure({
                HTMLAttributes: {
                    class: 'list-decimal pl-13'
                }
            })
        ],
        editorProps: {
            attributes: {
                class:
                    "flex flex-col px-6 py-3 justify-start border-b border-r text-black border-l border-gray-700  items-start w-full gap-3 pt-4 rounded-bl-md rounded-br-md outline-none"
            }
        },
        onUpdate: ({ editor }) => {
            handleChange1(editor.getHTML());
        },
    })

    return (
        <>
            <div className='w-full px-4'>
                <Toolbar editor={editor} content={content}></Toolbar>
                <EditorContent style={{ whiteSpace: "pre-line" }} editor={editor} />
            </div>

        </>

    )
}


//tiptap svg button
<button
                        onClick={(e: any) => {
                            e.preventDefault()
                            editor.chain().focus().toggleHeading({ level: 1 }).run()
                        }}
                        className={
                            editor.isActive("heading", { level: 1 })
                                ? "bg-slate-500 text-white p-2  text-3xl rounded-lg"
                                : "text-bold text-3xl"
                        }

                    >
                        <Heading1 className="w-5 h-5" />
                    </button>
                    <button
                        onClick={(e: any) => {
                            e.preventDefault()
                            editor.chain().focus().toggleHeading({ level: 2 }).run()
                        }}
                        className={
                            editor.isActive("heading", { level: 2 })
                                ? "bg-slate-500 text-white p-2 rounded-lg"
                                : "text-bold"
                        }

                    >
                        <Heading2 className="w-5 h-5" />
                    </button>

Not only for h1 and h2, even block quotes are working the codeblock doesn’t highlighting any color, just display as plain text viewed official documentation of tiptap, but documentation didn’t resolved this error, what factor would resisting this behaviour?

Node js:whats wrong with my proxy code? the js code works fine while not using the proxy but once i use the proxy it just says internal server issue

/* The error type is always CORS, even while i disabled CORS. The error also always points to the fetch request.
Could this be due to roblox rejecting the request? or would that not cause an inernal server error
heres the code:

I tried disabling the cors, didnt work. Disabling the proxy just gives a CORS error because roblox api dosent allow you to make api calls from non-roblox websites. None of the console logs display anything,and neither does winston. It seems like no changes i make to the proxy code do anything. (the project structure is like this

project
node modules
Proxy (folder)
proxy script
js script
*/

    const express = require("express");
    const axios = require("axios");
    const cors = require("cors");
    const morgan = require("morgan");
    const app = express();
    const port = 3000;
    app.use(cors());

    app.use(morgan("combined"));

    app.use((req, res, next) => {
      const origin = req.headers.origin;
      const allowedOrigins = ["http://127.0.0.1:8080"];
      if (allowedOrigins.includes(origin)) {
        res.setHeader("Access-Control-Allow-Origin", origin);
      }
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      next();
    });

    app.all("/proxy", async (req, res) => {
      try {
        const response = await axios({
          method: req.method,
          url: "https://auth.roblox.com",
          headers: req.headers,
          data: req.body,
        });

        res.status(response.status).send(response.data);
        console.log(response.data);
      } catch (error) {
        console.error("Proxy error:", error);

        if (error.response) {
          res.status(error.response.status).send(error.response.data);
          console.error("Roblox API error:", error.response.data);
        } else {
          console.log("Control flow reached the else block");
          console.log("Error object:", error);
          res.status(500).send("Proxy error ");
        }
      }
    });

    app.listen(port, () => {
      console.log(`Proxy server listening at http://localhost:${port}`);
    });

What is the use of getElementById [closed]

while writing in javascript file, what is the use of document.getElementById()

provide the use of document.getElementById() in javascript file

and is this is correct document.getElementById() is a fundamental tool in JavaScript for accessing and manipulating specific elements within a webpage, enabling dynamic and interactive web development? And it is useful for accessing the element? And changing the particular functionality of an element

problem in saving in local storage of browser [closed]

I aim to create a multi-timer website where the timer continues running regardless of whether the page is open or closed. I’ve attempted to implement this using local storage, but it’s not functioning properly. Should I move my website to the server side? Perhaps by creating databases for the timers using MongoDB and Node.js?

JavaScript does not show methods and properties

dear programmers.
I have only recently started learning JavaScript and therefore started installing and configuring Visual Studio Code to work with JS.

In the main index file.js everything works correctly and the hints display methods and properties.
An event is triggered here and we run the execute method to execute the command.
We pass an argument with a certain type to the command.
The file index.js:

client.on(Events.InteractionCreate, async interaction => {
    await command.execute(interaction);
}

But in the command, this type is not recognized and shows the type any. Properties and methods are not displayed. I do not know how to cast types in javascript.
Is there any way to display properties and methods automatically? Maybe there are extensions?
The file command.js:

async execute(interaction) {
    // parameter interaction: any
    await interaction.reply(`Reply`);
}

Thank you very much. I’m just learning and I’ll be glad if you help me)))

I have successfully configured jsconfig.js, so that the program hints work for js.
The file jsconfig.js:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES6"
  },
  "exclude": ["node_modules"]
}

Not able to redirect to my dashboard.PHP file while using Google Signin API?

the code which im using is–>

    <div class="login">
        <form method="POST">
            <label for="chk" aria-hidden="true">Login</label>
            <input type="email" name="login_email" placeholder="Email" required="">
            <input type="password" name="login_password" placeholder="Password" required="">
            <button type="submit" name="login">Login</button>

            <div class="containergg">
                <label1 for="signup">Or signin with:</label1>
            </div>
            <div class="g-signin2" data-onsuccess="onSignIn"></div>
            <script>
                function onSignIn(googleUser) {
                    // Extract necessary information about the user
                    var profile = googleUser.getBasicProfile();
                    var userEmail = profile.getEmail();

                    // Check if user is signed in with Google
                    if (userEmail) {
                        // Redirect to dashboard.php
                        window.location.href = 'dashboard.php';
                    } else {
                        // Handle the case where the user is not signed in
                        console.log('User not signed in.');
                    }
                }
            </script>
        </form>
    </div>

same logic for signup

I’m expecting, after sign in it should take me to dashboard.php file.`