How can i use ajax function for like

i have like.php file which counts and shows the number of likes. How can i add ajax function to do this without reloading page?

<a href="<?=ROOT?>like/post/<?php echo $ROW['postid'] ?>"><img src="/icons/like.png" style="height:25px"><?php echo $likes ?></a> . 

ERROR TypeError: Cannot read properties of undefined (reading ‘value’) at MatKeyboardKeyComponent._setCursorPosition

In my project, I’m using ngx7-material-keyboard for the virtual keyboard all this code was written long back they didn’t use formGroup, when I enter any kay in the virtual keyboard I’m getting this error ERROR TypeError: Cannot read properties of undefined (reading ‘value’) at MatKeyboardKeyComponent._setCursorPosition and also not able get the events.

Please help me to fix this issue,
I really appreciate any help you can provide.

I tried with keyup event to take user entered data but it is not working, I want to capture the user entered data

I cannot extend the express request interface/type

I have extended the request interface that express.js provided to a custom one that want to use but I am getting an error when I type annotate the request object in the request handler with my custom request interface.

the error says

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(request: Request, response: Response, next: NextFunction) => Promise<void>' is not assignable to parameter of type 'Application<Record<string, any>>'.
      Type '(request: Request, response: Response<any, Record<string, any>>, next: NextFunction) => Promise<void>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more.

This is my custom request interface file interfaces/Request.ts

import { Request as ExpressRequest } from "express";
import { User } from "@prisma/client";

interface Request extends ExpressRequest {
  id: string;
  user: User;
}

export default Request;

This is one of my request handlers controllers/auth/login.ts

import { Response } from "express";

import Request from "../../interfaces/Request";

const loginHandler = async (request: Request, response: Response) => {};

export default loginHandler;

and this is my auth router routers/auth.ts

import { Router } from "express";

import loginHandler from "../controllers/auth/login";

const authRouter = Router();

authRouter.get("/login", loginHandler);

export default authRouter;

This is my routers/index.ts which I use to export all the routers

import authRouter from "./auth";

const routers = [
  {
    path: "/auth",
    routeHandler: authRouter,
  },
];

export default routers;

This is my main file server.ts

import express from "express";

// App routers
import routers from "./routers";

const app = express();

const useRouters = () => {
  routers.forEach(({ path, routeHandler }) => {
    app.use(path, routeHandler);
  });
};
useRouters();

const port = process.env.PORT || '3500'

app.listen(port, () => {
  console.log(`Server is listening on ${port}`);
});

Those were my files that are related to my custom request interface

Note: when I remove my custom request interface annotation and use the express request interface I get no error

jwt malformed message in jwt token

here when i requests the get method it gives the error of jwt malformed
here the json says
i have also tried by adding multiple token format but didn’t worked

{
    "status": "error",
    "error": {
        "name": "JsonWebTokenError",
        "message": "jwt malformed",
        "statusCode": 500,
        "status": "error"
    },

and the code is



const {promisify}=require('util');
const jwt =require('jsonwebtoken')
const User=require('./../modals/userModal');
const catchAsync=require('../utils/catchAsync');               
const AppError=require('./../utils/appError');

const signToken=id=>{                                          
    return jwt.sign({                                          /
        id:id
    },process.env.JWT_SECRET,{  
        expiresIn:process.env.JWT_EXPIRES_IN
    }
    )
}


exports.signup=catchAsync(async(req,res,next)=>{

    const newUser=await User.create({
        name:req.body.name,                                             
        email:req.body.email,
        password:req.body.password,
        passwordConfirm:req.body.passwordConfirm,

    });

    const token=signToken(newUser._id)

    res.status(201).json({
        status:'success',
        token:token,
        data:{
            user:newUser
        }
     })
    });

//=========================================IMPLEMENTING LOGIN LOGIC============================================

    exports.login= catchAsync(async(req,res,next)=>{
        const {email,password}=req.body;
        
        //1). CHECK IF EMAIL AND PASS. EXIST OR NOT 
              if(!email || !password){
                  return next(new AppError('Please Provide Email and Password',400))
              }
 
        //2). CHECK IF USER EXISTS && PASSWORD IS CORRECT
              const user=await User.findOne({email}).select('+password');                    
            

              if(!user || !(await user.correctPassword(password, user.password))){             
                return next(new AppError('Incorrect email or password',401))
              }
        //3). IF EVERYTHING OKAY , SEND TOKEN TO CLIENT
               const token=signToken(user._id);
               res.status(200).json({
                status:'success',
                token
               })
    } );

//=======================================MIDDLEWARE FUNCTION FOR PROTECTED ROUTES==================================
                                                                                      
exports.protect=catchAsync(async(req,res,next)=>{
     

                                                                                        
       let token;                                                                        
        if(                                                                                      req.headers.authorization && 
        req.headers.authorization.startsWith('Bearer')
      ){
         token=req.headers.authorization.split(' ')[1];                          
        }
         console.log(token);

        if(!token){
            return next(new AppError('Your are not logged in! please login to get access',401))
        }



   const decoded=await promisify(jwt.verify)(token,process.env.JWT_SECRET)                              
   console.log(decoded);





                                                                                            //if 
next();
})

i have tried by applling multiple typed token format ddfdfd.dfdsfdg.gsgsdgds but this also didn’t work also there is no output of the decoded in console

NextJS – How to Set Cookie in route handler when having a separate backend

Background
My Application is consisted of a NextJS frontend and a NestJS backend.
The login flow is as below

1. NextJS sends POST request from a Client Component to the NestJS backend

LoginButton.tsx

...

export function LoginButton() {
  const login = async (credentialResponse: CredentialResponse) => {
     const loginRes = await axios.post(
       "http://localhost:3001/auth/google-login",
       {
         token: credentialResponse.credential,
       }
     );
  };
  ...
}

2. NestJS backend receives and process the request, then send the response with cookie

auth.controller.ts

...

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @Public()
  @Post('google-login')
  async login(...) {
    const loginRes = await this.authService.goolgeLoginIn(loginDto.token);

    res.cookie('accessToken', loginRes?.accessToken, {
      expires: new Date(new Date().getTime() + 1 * 60 * 60 * 1000), // 1 hr
      sameSite: 'strict',
      httpOnly: true,
    });

    return res.send(loginRes);
  }

  @Post('logout')
  async logout(@Response() res: ExpressResponse) {
    res.cookie('accessToken', '', { expires: new Date() });

    return res.send(201);
  }
}

3. NextJS frontend receives the response
The response is successful. When I inspector in Chrome Inspector > Application > Cookie,
I can see the cookie accessToken

Problem
Now I am trying to use App Router feature – Route Handler for the login api call.

app/api/auth/google-login/route.ts

...

export async function POST(request: NextRequest) {
  const { token } = await request.json();

  const loginRes = await axios.post(
    "http://localhost:3001/auth/google-login",
    {
      token: token,
    }
  );

  return NextResponse.json(loginRes.data, { status: 201 });
}

LoginButton.tsx

...

export function LoginButton() {
    fetch("/api/auth/google-login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ token: credentialResponse.credential }),
    });
  ...
}

However, even the api returns successful, the cookie accessToken is not set in the browser.
Why is that? Is there extra thing I have to do

How do I make my inputs from the form update the books list with a new object?

HTML

<body>
    <button onclick="OpenForm()" class="open-button">Add Book</button>
    <div id="myForm" class="form-popup">
      <form action="blah" type="get">
        <input type="text" name="author" onkeyup="formChanged" onchange="formChanged" />
        <label for="author">Author</label>
        <input type="text" name="title" onkeyup="formChanged" onchange="formChanged" />
        <label for="title">Title</label>
        <input type="number" name="pages" onkeyup="formChanged" onchange="formChanged" />
        <label for="pages">Pages</label>
        <input type="button" value="Submit" onclick="AddBookToLibrary()">
      </form>
    </div>
    <ul id="list"></ul>
ylibrary = [{
    author: "James",
    title: "James",
    pages: 15,

},
{
    author:"Jace",
    title:"Jace",
    pages: 16,


}]
function Books() {
    let book = {
    author: document.getElementsByName("author"),
    title: document.getElementsByName("title"),
    pages: document.getElementsByName("pages"),
    }
    return book
    
}
function AddBooktoLibrary() {
    let added = Books();
    mylibrary.push(added)

}
function OpenForm () {
    document.getElementById("myForm").style.display = "block";
    GenerateList()
        
}
function Closeform() {
    document.getElementById("myForm").style.display = "none";
}
let list1 = 0;
function GenerateList() {
    let lst = document.createElement("list");
    for (i = list1; i < mylibrary.length; i++) {
        let li = document.createElement('li')
        li.innerText = Object.values(mylibrary[i]);
        list.appendChild(li);
        list1 = mylibrary.length
        
        

    }

}

In the HTML Code I have a form named myForm that shows up when tyou click Add Book button that should take inputs and transfer them to the Books function to create a book object when the submit button is pressed. Then the book object is added to the Mylibrary when the AddBookToLibrary is called for the submit button. Afterwards if you click the Add Book function the printed list should be updated with the new book information. However the information does not update and the list doesnt. I know the list looks bad, I am just focusing on the inputs themselves working rn.

“Vapid public key must be a URL safe Base 64” web-push error in nodejs

I faced to a error from web-push library in my nodejs backend app.
When I want to set public key and private key in web-push with webpush.setVapidDetails()
I received an error in my terminal that said: “Error: Vapid public key must be a URL safe Base 64”
Please help me to fix it.

    webpush.setVapidDetails(
    "mailto:[email protected]",
    process.env.VAPID_PUBLIC_KEY,
    process.env.VAPID_PRIVATE_KEY
    );

and I tried to use some different ways for example:

    const publicKey = base64url.toBase64(process.env.VAPID_PUBLIC_KEY);
    const privateKey = base64url.toBase64(process.env.VAPID_PRIVATE_KEY);

but it doesn’t work.

How to ensure only one video plays at a time in React application?

I’m building a React application where I have multiple video components rendered dynamically. I want to ensure that only one video plays at a time, and when a new video starts playing, the previously playing video should pause.

I have a RenderVideoSources component that maps over an array of video sources and renders individual VideoPlayer components for each source. Here’s a simplified version of my code structure:

// RenderVideoSources.tsx
import { useState } from "react";
import type { Source } from "../page";
import VideoPlayer from "./video-player";

export interface RenderVideoSourceTypes<T = unknown> extends Source {
  key?: T;
}

const audioPlayer = () => <></>;

const RenderVideoSources = (props: RenderVideoSourceTypes, index: any) => {
  const component: { [component: string]: React.ElementType<any> } = {
    audio: audioPlayer,
    video: VideoPlayer,
  };

  const [activeIndex, setActiveIndex] = useState();

  const Component = component[props.type];

  const handlePlayEvent = (currentIndex: any) => {
    setActiveIndex(currentIndex);
    return;
  };

  if (props.type === "video") {
    return (
      <div
        className="flex justify-center items-center"
        key={props.key || index}
      >
        <div className="w-3/4 py-4">
          <Component
            source={props.src}
            isPlaying={activeIndex === index}
            onPlay={() => handlePlayEvent(index)}
          />
        </div>
      </div>
    );
  }

  // return <Component key={props.key || index} src={props.src} />;
};

export default RenderVideoSources;

And here’s the VideoPlayer component:

// VideoPlayer.tsx
"use client";

import {
  MediaCanPlayDetail,
  MediaCanPlayEvent,
  MediaPlayer,
  MediaPlayerInstance,
  MediaProvider,
  MediaViewType,
  Poster,
} from "@vidstack/react";
import { useEffect, useRef, useState } from "react";

import { VideoLayout } from "../layout/video-layout";

import "@vidstack/react/player/styles/default/theme.css";

import styles from "@/app/styles/player.module.css";

export interface VideoPlayerProps {
  source: string;
  isPlaying: boolean;
  onPlay: () => void;
}

const VideoPlayer = ({ isPlaying, source, onPlay }: VideoPlayerProps) => {
  const videoRef = useRef<MediaPlayerInstance>(null);

  const [src, setSrc] = useState("");
  const [viewType, setViewType] = useState<MediaViewType>("unknown");

  useEffect(() => {
    if (source) setSrc(source);
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.play();
      } else {
        videoRef.current.pause();
      }
    }
  }, [source, isPlaying]);

  useEffect(() => {
    return () => {
      setSrc("");
      setViewType("unknown");
    };
  }, []);

  return (
    <div>
      {src && (
        <MediaPlayer
          className={`${styles.player} media-player`}
          title="Sprite Fight"
          src={src}
          crossOrigin
          playsInline
          onPlay={onPlay}
          // paused={isPlaying}
          ref={videoRef}
        >
          <MediaProvider>
            {viewType === "video" && (
              <Poster
                className={`${styles.poster} vds-poster`}
                src="https://image.mux.com/VZtzUzGRv02OhRnZCxcNg49OilvolTqdnFLEqBsTwaxU/thumbnail.webp?time=268&width=1200"
                alt="Girl walks into campfire with gnomes surrounding her friend ready for their next meal!"
              />
            )}
          </MediaProvider>
          <VideoLayout thumbnails="https://image.mux.com/VZtzUzGRv02OhRnZCxcNg49OilvolTqdnFLEqBsTwaxU/storyboard.vtt" />
        </MediaPlayer>
      )}
    </div>
  );
};

export default VideoPlayer;

I’m struggling with implementing the logic inside the handlePlayEvent function to achieve the desired behavior. How can I ensure that only one video plays at a time and others pause when a new video starts playing?

Any help or guidance would be greatly appreciated. Thank you!

Remove the duplicates

How to remove the duplicate strings in an array. I tried this which doesn’t workout.

var input = ['john','john','rio','ravi','josva','ravi'];

    let remove = function(){
    let result = [];
    for (let i = 0; i<input.length; i++){
        if(input[i] == input[i]){
            return false;
        }else{
            return true;
        }
    }
    result.push(input[i]);
    console.log(result);
    };
remove();

Why is my Ref showing up as Undefined? (React)

I am using the UseRef hook to create a Ref variable and inserting that into one of the components in my return statement. ‘AnimationComponent’ has it’s own tags which return some inner elements.

The basic outline of my code is like this:

var refVar1 = useRef();

useEffect(()=>{
    console.log("value of refVar1 : " + refVar1);
    console.log("value of refVar1.current : " + refVar1.current);
}, [])


return(
  <g>
     <path>
        <AnimationComponent ref={refVar1}>
     </path>
  </g>
)

I’m finding that the value of refVar1 and refVar1.current are always undefined.

Which makes me wonder what how is the code really flowing in React? Once ‘AnimationComponent’ is rendered, does that mean that the code within the useEffect will never execute afterwards?

I always thought all the code in React components is ” asynchronous ” in a way. Even when inner children components are rendered, the code in the parents will still execute simultaneously?

I have tried putting those console log statements inside UseEffects and outside them. They always show as undefined.

Google Map Api with Spring MVC thymeleaf

I have a problem about Google Map Api by using spring mvc and thymeleaf.
In this code I got once state location by selected.But when I didn’t select anything,I want all of that State’s location.How can I do it?

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkMUEDzZ_3CHXPpxdzMriVb7a8avF0Wfc&callback=initMap" async defer></script>

    <script th:inline="javascript">

        var stateCoordinate = {
            "Yangon" : {lat: 16.8409,lng: 96.1735},
            "Mandalay" : {lat: 21.9588,lng: 96.0891},
            "NayPyiThaw" : {lat: 19.7633,lng: 96.0785},
            "Chin" : {lat:22.0087,lng: 93.5813},
            "Yakhine" : {lat:20.1041,lng:93.5813},
            "Shan" : {lat:22.0362,lng:98.1339}
        };
        var map;
        var marker;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map_div'), {
                center: {lat: 16.8409, lng: 96.1735},
                zoom: 8
            });

            var stateSelect = document.getElementById('stateSelect');
            stateSelect.addEventListener('change',function (){
                var selectState = this.value;
                var coordinates = stateCoordinate[selectState];

                if (coordinates) {
                    map.setCenter(coordinates);
                    placeMarker(coordinates);
                }
            });

        }

        function placeMarker(location){
            if (marker){
                marker.setPosition(location);
            }else{
                marker = new google.maps.Marker({
                    position: location,
                    map: map
                });
            }
        }
    </script>

I hope it got me a little help for finding all state’s location

How can I check if the every department’s months is existing while comparing it to the`monthsName` array using `startMonth` and endMonth`

How can I check if the every department’s months is existing while comparing it to themonthsName array using startMonth and endMonth`

I’m sorry I can’t explain the words properly, This is my alternative to my previous question How can I return it as a 0 instead of skipping the month in SQL?

This is the code I run after getting the result to the database, it simply group the deparment’s event_count by department and by month.

function groupDataByDepartment(results, startMonth, endMonth) {
        
        const monthNames = [
          { abbreviation: "Jan", number: 1 },
          { abbreviation: "Feb", number: 2 },
          { abbreviation: "Mar", number: 3 },
          { abbreviation: "Apr", number: 4 },
          { abbreviation: "May", number: 5 },
          { abbreviation: "Jun", number: 6 },
          { abbreviation: "Jul", number: 7 },
          { abbreviation: "Aug", number: 8 },
          { abbreviation: "Sep", number: 9 },
          { abbreviation: "Oct", number: 10 },
          { abbreviation: "Nov", number: 11 },
          { abbreviation: "Dec", number: 12 },
        ];
        
        const groupedData = {};
        let currentID = 1; // Initialize ID counter
        let currentDepartment;
    
        results.forEach((entry) => {
            const { department, year, month, event_count } = entry;
    
            if (department !== currentDepartment) {
                currentDepartment = department;
                currentID = 1; // Reset ID counter when department changes
            }
    
            if (!groupedData[department]) {
                groupedData[department] = [];
                
            }
    
            groupedData[department].push({
                id: currentID++,
                [month]: event_count,
                year: year,
            });
        });
    
        return groupedData;
    }


const groupedData = groupDataByDepartment(sampleResult, 12, 1)

Now the result will be like this

sampleResult = [
    {
        "department": "Department 1",
        "year": 2022,
        "month": "Dec",
        "event_count": 36
    },
    {
        "department": "Department 1",
        "year": 2023,
        "month": "Jan",
        "event_count": 28
    },
    {
        "department": "Department 2",
        "year": 2022,
        "month": "Dec",
        "event_count": 8
    },
    {
        "department": "Department 2",
        "year": 2023,
        "month": "Jan",
        "event_count": 50
    },
    {
        "department": "Department 3",
        "year": 2022,
        "month": "Dec",
        "event_count": 1
    },
    {
        "department": "Department 3",
        "year": 2023,
        "month": "Jan",
        "event_count": 34
    },
    {
        "department": "Department 4",
        "year": 2023,
        "month": "Jan",
        "event_count": 11
    },
    {
        "department": "Department 5",
        "year": 2022,
        "month": "Dec",
        "event_count": 2
    },
    {
        "department": "Department 5",
        "year": 2023,
        "month": "Jan",
        "event_count": 21
    },
    {
        "department": "Department 6",
        "year": 2022,
        "month": "Dec",
        "event_count": 17
    },
    {
        "department": "Department 6",
        "year": 2023,
        "month": "Jan",
        "event_count": 72
    },
    {
        "department": "Deparment 7",
        "year": 2022,
        "month": "Dec",
        "event_count": 38
    },
    {
        "department": "Deparment 7",
        "year": 2023,
        "month": "Jan",
        "event_count": 14
    },
    {
        "department": "Department 8",
        "year": 2022,
        "month": "Dec",
        "event_count": 44
    },
    {
        "department": "Department 8",
        "year": 2023,
        "month": "Jan",
        "event_count": 132
    }
]

What i’m trying to achieve is with the use of startMonth and endMonth. I want to loop and compare the monthsName and the sampleResult and if the month is not existing, still input the month its misssing but make the result as 0

  • startMonth = 12
  • endMonth = 1

So in the sampleResult in the Department 4. The function skip the month of Dec, because I don’t have any data during Dec, instead of leaving it blank, I want it to be like this.

sampleResult = [
      ...other results
    {
        "department": "Department 4",
        "year": 2022,
        "month": "Dec",
        "event_count": 0
    },
     {
        "department": "Department 4",
        "year": 2023,
        "month": "Jan",
        "event_count": 11
    },

]

CORS CI4 /public folder (kml file) when access from frontend Nuxt JS

i want to access kml file from my backend

try {
          for (const city of this.cities) {
            if (!city || !city.kml) {
              continue;
            }

            const baseURL = `http://localhost:8080`;
            const kmlFilePath = baseURL + city.kml;

            Omnivore.kml(kmlFilePath).addTo(customIcons);
          }
        } catch (error) {
          console.error('Error fetching or adding KMZ file:', error);
        }

but i get cors error :
Access to XMLHttpRequest at ‘http://localhost:8080/uploads/transmitters/kmz/Untitled.kml’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
client.js:775

GET http://localhost:8080/uploads/transmitters/kmz/Untitled.kml net::ERR_FAILED 200 (OK)

i have my cors setting :

    public function before(RequestInterface $request, $arguments = null)
    {

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        header('Access-Control-Allow-Credentials: true');
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS") {
            die();
        };

    }

i tried to access the file from my fe, yes it works. but when the app is build, and i want to update or add new kml, i cant?

VSCode: IntelliSense assumes “wrong” Path with CommonJS Modules and Electron

I have an Eletron application with the following path structure

/
|-index.html
|-js/
|--foo.js
|--bar.js

foo.js and bar.js are CommonJS modules. Now I want to include foo in bar with require.
For Electron the base directory is / so require must look like this:

const foo = require('./js/foo.js');

Works so far.
But I would like to have Intellisense for foo, according to VSCode I had to omit the folder in reqiure:

const foo = require('./foo.js');

Then I have Intellisense, but my application can’t find the module.