req.body giving an empty object {} only in case of api/vi/user/login route

req.body is empty in Node.js Express API route when sending JSON request using Postman.

This is the error:

<pre>Error: Username or email is required<br> &nbsp; &nbsp;at file:///C:/Users/hrshl/OneDrive/Desktop/Harshal/Web%20dev/vdeohub-backend/src/controllers/user.controller.js:117:15</pre>

This part is causing the error:

if (!username && !email) {
        throw new ApiError(400, 'Username or email is required');
}

This is the loginUser function which was giving the error:

const loginUser = asyncHandler(async (req, res) => {
    // Take the data from the frontend - username/email and password
    // Validate the user details - if all fields are present or not
    // Check if the username/email exists in database
    // If yes, check if the password is correct or not using isPasswordCorrect method
    // create an access token and a refresh token+
    const generateAccessAndRefreshTokens = async (userId) => {
        try {
            user = User.findById(userId);
            const accessToken = user.generateAccessToken();
            const refreshToken = user.generateRefreshToken();

            user.refreshToken = refreshToken;
            user.save({ validateBeforeSave: false });

            return { accessToken, refreshToken };
        } catch (error) {
            return new ApiError(
                500,
                'Something went wrong while generating access and refresh tokens'
            );
        }
    };

    const { username, email, password } = req.body;

    // console.log(req.body);    

    if (!username && !email) {
        throw new ApiError(400, 'Username or email is required');            //error from here
    }

    const user = await User.findOne({
        $or: [{ username }, { email }],
    });

    if (!user) {
        return new ApiError(404, 'User does not exists');
    }

    if (!password) {
        return new ApiError(400, 'Password is required');
    }

    const isPasswordValid = user.isPasswordCorrect(password);

    if (!isPasswordValid) {
        throw new ApiError(401, 'Invalid user credentials');
    }

    const { accessToken, refreshToken } = await generateAccessAndRefreshTokens(
        user._id
    );

    const loggedInUser = User.findById(user._id).select(
        '-password -refreshToken'
    );

    options = {
        httpOnly: true,
        secure: true,
    };
    

    return res
        .status(200)
        .cookie('refreshToken', refreshToken, options)
        .cookie('accessToken', accessToken, options)
        .json(
            new ApiResponse(
                200,
                { user: loggedInUser, accessToken, refreshToken },
                'User logged in successfully'
            )
        );
});

This is the asyncHandler utility:

const asyncHandler = (requestHandler) => {
    return (req, res, next) => {
        Promise.resolve(requestHandler(req, res, next)).catch((err) =>
            next(err)
        );
    };
};

export { asyncHandler };

This is the user model:

import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
import JWT from 'jsonwebtoken';

const userSchema = new mongoose.Schema(
    {
        username: {
            type: String,
            required: [true, 'Username is required...'],
            unique: true,
            lowercase: true,
            trim: true,
            index: true,
        },
        email: {
            type: String,
            required: [true, 'Email is required...'],
            unique: true,
            lowercase: true,
            trim: true,
        },
        fullName: {
            type: String,
            required: [true, 'Full name is required...'],
            trim: true,
            index: true,
        },
        avatar: {
            type: String, //Cloudinary URL
            required: [true, 'Avatar is required...'],
        },
        coverImage: {
            type: String, //Cloudinary URL
        },
        watchHistory: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'Video',
            },
        ],
        password: {
            type: String,
            required: [true, 'Password is required...'],
            minlength: [6, 'Password must be at least 6 characters...'],
        },
    },
    {
        timestamps: true,
    }
);

userSchema.pre('save', async function (next) {
    if (this.isModified('password')) {
        this.password = await bcrypt.hash(this.password, 10);
    }
    next();
});

userSchema.methods.isPasswordCorrect = async function (password) {
    return await bcrypt.compare(password, this.password);
};

userSchema.methods.generateAccessToken = function () {
    return JWT.sign(
        {
            _id: this._id,
        },
        process.env.ACCESS_TOKEN_SECRET,
        {
            expiresIn: process.env.ACCESS_TOKEN_EXPIRY,
        }
    );
};

userSchema.methods.generateRefreshToken = function () {
    return JWT.sign(
        {
            _id: this._id,
        },
        process.env.REFRESH_TOKEN_SECRET,
        {
            expiresIn: process.env.REFRESH_TOKEN_EXPIRY,
        }
    );
};

export const User = mongoose.model('User', userSchema);

If you need to look at the entire codebase, head to my GitHub repo.

There is also a registerUser function, and it also takes in arguments from req.body, but that one works perfectly fine:

const registerUser = asyncHandler(async (req, res) => {
    // get user details from frontend
    // validate the user details - if all the fields are present or not
    // check if user already exixts in database - username, email
    // if user exists send error response to frontend
    // check if the user has uploaded a profile picture/avatar
    // if yes, upload the image to cloudinary
    // check for the image uploaded to cloudinary successfully or not
    // if yes, save the user details to a new user object
    // create a new user in the database
    // remove the password and the refreshToken from the response
    // check for user creation success or failure
    // if success, send the response to the frontend

    const { fullName, email, username, password } = req.body;
    console.log(req.body);

    if (
        [fullName, email, username, password].some(
            (field) => field?.trim() === ''
        )
    ) {
        throw new ApiError(400, 'All fields are required');
    }

    const existedUser = await User.findOne({
        $or: [{ email }, { username }],
    });

    if (existedUser) {
        throw new ApiError(409, 'User already exists');
    }

    console.log(req.files);

    const avatarLocalPath = req.files?.avatar[0]?.path;
    const coverImageLocalPath = req.files?.coverImage?.[0]?.path;

    if (!avatarLocalPath) {
        throw new ApiError(
            400,
            'Avatar is required. Avatar not found in request body'
        );
    }

    const avatar = await uploadToCloudinary(avatarLocalPath);

    let coverImage;
    if (!(coverImageLocalPath === undefined)) {
        coverImage = await uploadToCloudinary(coverImageLocalPath);
    }

    if (!avatar) {
        throw new ApiError(
            400,
            'Avatar is required. Failed to upload avatar to cloudinary'
        );
    }

    const user = await User.create({
        fullName: fullName,
        email: email,
        username: username.toLowerCase(),
        password: password,
        avatar: avatar.url,
        coverImage: coverImage?.url || '',
    });

    const createdUser = await User.findById(user._id).select(
        '-password -refreshToken'
    );

    if (!createdUser) {
        throw new ApiError(500, 'Failed to create user. Something went wrong.');
    }

    return res
        .status(201)
        .json(new ApiResponse(200, createdUser, 'User created successfully'));
});

I tried console logging the entire request, and it was fine, just the request.body was empty. I also tried adding bodyparser, but it didn’t do anything. I also tried changing the check to:

if (!(username || email)) {
        throw new ApiError(400, 'Username or email is required');
}

but still no luck.

jQuery each().height() in native JS

My goal is to have the same height for all bootstrap card-headers, card-bodys and card-footers. I couldn’t find a way to do this without JS.
I found a jQuery Code (https://codepen.io/felinuxltda/pen/KKVVYYN?editors=1111)

var x = 0;
$(".card-deck .card-header, .card-deck .card-footer")
  .each(function (id, it) {
    if ($(it).height() > x) {
      x = $(it).height();
    }
  })
  .height(x);
});

I converted this code to native JS but I have to loop multiple times.

var header = 0;
var body = 0;
var footer = 0;
document.querySelectorAll(".card-header, .card-body, .card-footer").forEach(function (element){
    if (element.classList.contains('card-header')){
        if (element.offsetHeight > header) {
            header = element.offsetHeight;
        }
    } else if (element.classList.contains('card-body')){
        if (element.offsetHeight > body) {
            body = element.offsetHeight;
        }
    } else if (element.classList.contains('card-footer')){
        if (element.offsetHeight > footer) {
            footer = element.offsetHeight;
        }
    } 
});
document.querySelectorAll(".card-header").forEach(function (element){
    element.style.height = header;
});
document.querySelectorAll(".card-body").forEach(function (element){
    element.style.height = body;
});
document.querySelectorAll(".card-footer").forEach(function (element){
    element.style.height = footer;
});

I wonder if there is a similar way to do jQuery “each().height()” in native JS.

How can I fix error in Javascript in MVC Project?

I’m trying to add to cart using JavaScript in an MVC project, but I’m getting an error. Can anyone help? Or can anyone offer me a different alternative for this process?

I was expecting the post operation I made in JavaScript to directly write the JSON code on the controller side, but I encountered an error.

enter image description here

enter image description here

Why do I have frame dropped but no main script is used

I am currently trying to improve animations performances on my project. I have so issues with one animation that I don’t understand. The slowdowns occurs on devices not that old (Honor 9, Pixel 5). I am usually arround 20 fps, I would love to be above 30, or event at 60 (I am on a pixel 6a).

For context :

  • I use a requestAnimationFrame loop to play my animation.
  • I only modify opacity and transform on my elements.

I get a lot of frame drop but the main thread does not seems to be used at this point.

I’m adding the performances report to my message.
Performance report

As you can see, 1 have a lot of frame dropped from 2100ms to 2300ms, but not a lot is going on in the main thread, and I can’t figure why my frames are dropped. I know I have a long task (100ms) before and a long one (210ms) after, but can this be the cause of the drop ? I’ve try reducing it, but I feel like this does not impact my animation that much.

For my animations, I used the following code :

AnimatedValue.ts

export class AnimatedValue {
    startTime = 0;
    steps = 0;

    constructor(private readonly progressCallback: (progress: number) => void, private readonly duration = 1000) {}

    animate() {
        requestAnimationFrame((chrono) => {
            if (!this.startTime) {
                this.startTime = chrono;
                this.steps = 0;
            }
            const elapsedTime = chrono - this.startTime;
            const progress = elapsedTime / this.duration;
            if (progress < 1) {
                this.progressCallback(progress);
                this.animate();
                this.steps++;
            } else {
                this.progressCallback(1);
            }
        });
    }
}

Animate.ts

const animate = async (callback: (progress: number) => void, duration: number, onEnd = () => {}) => {
    return new Promise<void>((resolve) => {
        const animation = new AnimatedValue((progress) => {
            callback(progress);
            if (progress === 1) {
                requestAnimationFrame(() => {
                    onEnd();
                    resolve();
                });
            }
        }, duration);
        animation.animate();
    });
};


export const animateOpen = async (
    feedPlayerElement: HTMLElement,
    backgroundElement: HTMLElement | null,
    fromInformation: { originX?: number; originY?: number },
) => {
    const { originX = 50, originY = 50 } = fromInformation;
    feedPlayerElement.style.transformOrigin = `${originX}% ${originY}%`;

    await animate(
        (progress) => {
            feedPlayerElement.style.transform = `scale(${progress})`;
            if (backgroundElement) backgroundElement.style.opacity = progress.toString();
        },
        CLOSE_ANIMATION_DURATION,
        () => {
            feedPlayerElement.style.transform = '';
            feedPlayerElement.style.transformOrigin = '';
            if (backgroundElement) backgroundElement.style.opacity = '';
        },
    );
};

I am usually arround 20 fps, I would love to be above 30, or event at 60 (I am on a pixel 6a).

useGeolocation refresh many times

I’m new in React and I would use the hook useGeolocation but it’s refresh all the times. So I isolate this hook in a component Location but I can’t access to the position of the user and send to my component MapWrapper to center the map.

import { useGeolocation } from "@uidotdev/usehooks";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { AlertCircle } from "lucide-react"
import { MapWrapper } from "../mapWrapper";
import React, { forwardRef, useEffect, useRef } from "react";

export const Home = () => {
    const refLatLong = useRef()

    useEffect(() => {
        console.log(refLatLong.current?.getAttribute('position'))
    }, []);

    return (
        <>
            <Location ref={refLatLong} />
            <MapWrapper position={refLatLong.current} />
        </>
    ) 
}

const Location = forwardRef((props, ref) => {
    const location = useGeolocation();
    if (location.loading) {
        return <>
            <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertTitle>Chargement...</AlertTitle>
            <AlertDescription>
                Vous devez accepter la géolocalisation
            </AlertDescription>
            </Alert>
        </>
    }
    
    if (location.error) {
        return <>
            <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Chargement...</AlertTitle>
                <AlertDescription>
                    Activer les autorisations pour accéder à vos données de localisation
                </AlertDescription>
            </Alert>
        </>
    }

    return <div ref={ref} id="user-position" position={[location.latitude, location.longitude]}></div>

})

Could you tell me what is my error with the ref and if it’s the good solution.
Thanks a lot

Control Flow of async function in JavaScript

In this code, callback function of .then is executed before the console.log("still going on...") but normally callback function of .then shall be posted to micro stack first before coming to call stack.

What is happening differently here and why?

async function test(){
    console.log("start");
    console.log("going on...");
    await new Promise((resolve, reject) => {setTimeout(() => resolve("promise value"), 5000);})
    .then((result) => console.log(result))
    .catch((error) => console.log(error));
    console.log("still going on...");
}
test();
console.log("end.");

Output:

start
going on...
end.
promise value
still going on...

Is there a way to get a pop-in animated contact form, but without Javascript or queryselectors?

I was able to make a contact form like this work but I wasn’t able to make this work without Javascript. I want the form to pop in from the right side with a click on the “open” icon and then stay open until user closes the form with the “close” icon and then pop out back to the original state. Any assistance would be greatly appreciated. Thanks!

<button id="contact" type="button" onclick="openForm()"><div class="triangle-left"></div></button>
<div id="contactForm">
<div class="containerContact">
<form action="emailsend.php" method="post" enctype="text/plain">
<h3 class="formheading">CONTACT</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin blandit velit ut placerat suscipit.</p> <input type="text" name="name" placeholder="Name or Company*" size="75" autocomplete="on" required>
<input type="text" name="phone" placeholder="Phone*" size="75" autocomplete="on" required>
<input type="text" name="mail" placeholder="Email*" size="75" required>
<select name="project" required>
<option value="" disabled selected hidden>Test*</option>
<option value="1">Test</option>
<option value="2">Test</option>
<option value="3">Test</option>
<option value="4">Test</option>
<option value="5">Test</option>
</select>
<textarea class="messageInput" name="Message" placeholder="Message*" rows="7" cols="45" required></textarea>
<input class="sendButton" type="submit" value="Let's Chat!">
</form>
<button id="closeContact" type="button" onclick="closeForm()"><div class="triangle-right"></div></button>
</div>
</div>

CSS:

.triangle-left {
    width: 0;
    height: 0;
    border-top: 25px solid transparent;
    border-right: 50px solid #555;
    border-bottom: 25px solid transparent;
}

.triangle-right {
    width: 0;
    height: 0;
    border-top: 25px solid transparent;
    border-left: 50px solid #323;
    border-bottom: 25px solid transparent;
}

#contact {
    z-index: 200;
    background: none;
    border: none; 
    cursor: pointer;
    position: fixed;
    bottom: 10px;
    right: 30px;
    width: 60px;
}

#closeContact {
    z-index: 500;
    background: none;
    border: none; 
    cursor: pointer;
    position: fixed;
    bottom: 10px;
    right: 30px;
    width: 60px;
}

#contactForm {
    display: none;
    top: 0;
    height: 100%;
    z-index: 400;
    position: fixed; 
    background: lightblue;
}

#contactForm.open{
    display: block;
    transition: .5s linear;
    animation-name: formOpen;
    animation-duration: .5s;
    animation-fill-mode: forwards;
}

#contactForm.close{
    transition: .5s linear;
    animation-name: formClose;
    animation-duration: .5s;
    animation-fill-mode: forwards;
}

@keyframes formClose {
    from {right: 0;}
    to {right: -410px;}
}

@keyframes formOpen {
    from {right: -300px;}
    to {right: 0;}
}

.containerContact{
    padding: 25px;
    width: 300px;
    height: fit-content;
}

.formheading { 
    font-size: 30px; 
    color: #212529;
}

input[type=text]{
    margin: 0 auto;
    display: block;
    width: 100%;
    height: 20px;
    color: #212529;
    background: transparent;
    border: 1px;
    border-style: solid;
    border-color: #212529;
    font-size: 13px;    
}

select {
    margin: 0 auto;
    display: block;
    margin-top: 15px;
    padding-left: 8px;
    width: 100%;
    height: 40px;
    background: transparent;
    border: 1px;
    border-style: solid;
    border-color: #212529;
    font-size: 13px;
}

select:required:invalid {
  color: gray;
}
option[value=""][disabled] {
  display: none;
}
option {
  color: black;
}

.messageInput {
    margin: 0 auto;
    display: block;
    margin-top: 15px;
    padding: 8px;
    width: 100%;
    color: #212529;
    background: transparent;
    border: 1px;
    border-style: solid;
    border-color: #212529;
    font-size: 14px;
    font-family: sans-serif;
    resize: none;   
}

.sendButton {
    margin: 0 auto;
    display: block;
    cursor: pointer;
    margin-top: 15px;
    width: 100%;
    height: 40px;
    color: #FFF;
    background: #212529;
    border: 1px;
    border-style: solid;
    border-color: #212529; 
    transition: all 0.5s ease-out 0s
}

.sendButton:hover {
    background-color: #000;
}

JS

const Contact = document.querySelector("#contactForm");

function openForm() {
Contact.classList.add('open');
}
        
function closeForm() {
Contact.classList.add('close');
setTimeout(function(){
Contact.classList.remove('open');
Contact.classList.remove('close');
},300);
}

Details regarding micro-task queue checkpoints in Javascript

Based on this accepted answer regarding micro-task queue checkpoints in JS and looking up the concept more, I have come to understand the following:

Micro-task queue checkpoints happen at these points in the event loop:

  • After a script execution: When a JavaScript call stack finishes processing, the event loop will first run any pending microtasks before handling anything else.
  • After each macro task: Whenever a task from the task queue (e.g., event handler from a click) finishes, another microtask checkpoint occurs, again processing any microtasks before moving to the next macro task.

To understand this via an example, I tried the following code example:

setTimeout(() => {
    console.log('timeout1');
}, 3000);

setTimeout(() => {
    console.log('timeout2');
}, 3000);

let promise = new Promise(function (resolve, reject) {
    setTimeout(() => resolve('promise!'), 3000);
});

promise.then(
    (result) => console.log(result),
    (err) => console.log(err)
);

According to the concept of event-loops in JS, setTimeouts functions are pushed to the macro-task queue after the designated time passes. Thus, all three setTimeout tasks should be pushed on to the macro-task queue after 3 seconds have elapsed. On the other hand, the function passed to the .then() of the promise should be pushed to the micro-task queue. For the above code, at the beginning of a subsequent cycle, the first setTimeout task that was pushed to the macro-task queue should be run to print ‘timeout1’.

According to the micro-task queue checkpoint concept that I provided above, thereafter a checkpoint should occur and the print function in the micro-task queue should print ‘promise!’.

Finally, the second macro-task on the macro-task queue ‘timeout2’ should be printed.

However, running the code on the console of Chrome and Firefox (latest versions), and via Node v16.14.0 on my machine, I find the order of printing to be:

timeout1
timeout2
promise!

Is micro-task queue checkpoint behavior not guaranteed? If it is, am I mistaken somewhere else in my evaluation?

anchor tag not clicking inside a td table cell

table design

I have designed a table like above with the help of the code below:

I have added the code only of the hyperlink td tag.

Appearance wise, I got what I wanted. But, nothing happens when I click on the hyperlink. And clicking on hyperlink and td cell is the same. Where and what am I missing here?

var hiddenElement = document.createElement("a");
hiddenElement.setAttribute("href", blob);
hiddenElement.setAttribute("download", `row-${rowID}-${colID}.bin`);
hiddenElement.setAttribute("target", "_blank");
hiddenElement.textContent = 'Download Binary Object';
tdEl.appendChild(hiddenElement);
trEl.appendChild(tdEl);
tableBody.appendChild(trEl);
hiddenElement.click();
URL.revokeObjectURL(blob);

Why do firefox-based browsers react incorrectly to window.screenX/Y in my code?

I’m building a home website in which the window will create an illusion of transparency even when windowed and moved around in real time and I’m trying to use screenX and screenY for the cause (I should note that screenLeft and screenTop react the same).

In Google Chrome it reacts well, although the values are a bit weird (moving windowed windows on left edge will return -25)
In Firefox the function always returns 0, unless windowed, in that case it returns constant 25.
In Librewolf, the target browser, I always get constant 0. Letterboxing seems to have no effect.
Why is it that way, why only on Chrome and how can I fix this issue? I found no relevant fixes on this topic.
(If it’s relevant, which I doubt, I’m on linux with wayland)
Thanks beforehand.

The code in which I’m trying to utilize the functions:

const canvas = document.getElementById("background");
const context = canvas.getContext("2d");

var pozadi = new Image();
pozadi.src = "image.png";
var hod_x = window.screenX;
var hod_y = window.screenY;

pozadi.onload = function() {
  context.drawImage(pozadi, hod_x, hod_y, 2240, 1217, 0, 0, 2240, 1217);
}
body {
  margin: 0px
}
<canvas id="background" width="2240px" height="1217px"></canvas>

Android Webview evaluateJavascript returns null

I am trying to get username from webview. It returns null object.

webView.settings.javaScriptEnabled = true
webView.evaluateJavascript(
                    "(function() { return  document.getElementsByClassName('lgn-loginname') })();",
                    ValueCallback<String> { s ->
                        // 's' contains the result of the JavaScript evaluation
                        Log.d("JavaScript Result", "Result: $s")
                    }
                )

Also with this it is null.

webView.evaluateJavascript(
“(function() { var elements = document.getElementsByClassName(‘lgn-loginname’); ” +
“return elements.length > 0 ? elements[0].innerHTML })();”,
ValueCallback { s ->
// ‘s’ contains the result of the JavaScript evaluation
Log.d(“JavaScript Result”, “Result: $s”)
}
)

I tried many things and always getting null. What am I doing wrong?

Telegram bot get all messages

I made a telegram bot, received a token from it and now made it an administrator. How can I get through the bot all messages from the moment it was added? There are requests in this group and I need to get their full text.

https://api.telegram.org/bot<token>/getUpdates

{
    "ok": true,
    "result": [
        {
            "update_id": 523188842,
            "message": {
                "message_id": 3,
                "from": {
                    "id": 1087333324,
                    "is_bot": true,
                    "first_name": "Group",
                    "username": "GroupBot"
                }, 

             "sender_chat": {
                "id": -10021999992,
                "title": TITLE",
                "type": "supergroup"
            },

}

I receive a response after a getUpdate request, it contains the chat id and title, but how can I get the full text of the messages?

how to reverse array without using minus(-) sign and without using any In-build javascript methods in javascript? [closed]

how to reverse array without using minus(-) sign and reverse method in java-script?
I want to [“Apple”, “banana”, “orange”, “mango”, “straw-berry”] reverse this array and want output like this
[“straw-berry”, “mango”, “orange”, “banana”, “apple”]
but i want it without using any in built java-script method and without using minus(-) sign

Callback function in custom hook is not reruning

const selectedValueSet = new Set(selectedValues) const [selectedValues] = useSelectedValues(undefined, (value)=> selectedValueSet.has(value.id)|| undefined)

in this hook, when the selectedValueSet changes the callback is not rerunnng. it takes the initial value of selectedValueSet.

I dont want to modify the hook, but looking for a way to get updated value for selectedValues as selectedValueSet changes. basically I wanna see if theres a way of re-running the callback when selectedValueSet changes

I tried logging the value inside the callback,

but the value only gets logged once, so as I understand this callback only runs once even if the selectedValueSet changes