.env variables are undefined

Javascript says that my variables which are in .env are undefined. I’ve installed dotenv but it doesn’t work.

My index.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();
const router = express.Router();
const port = process.env.PORT || 5000;
const dotenv = require("dotenv");
const userRoute = require('./routes/user');
const authRoute = require('./routes/auth');



mongoose.set('strictQuery', false);
dotenv.config();
mongoose
    .connect(
        process.env.MONGODB_URL
    )
    .then(() => console.log("Database is working"))
    .catch((err) => {
        console.log(err)
    });
app.use(express.json());
app.use('', authRoute);


app.listen(process.env.PORT, function () {
    console.log('Server is up on port ' + process.env.PORT)
})

My auth.js

const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
const { response } = require('express');
const secretKey = process.env.SECRET_KEY;
//  Create a registration
console.log(secretKey);

router.post('/rejestracja', async (req, res)=>{
    const nowyUser = new User({
        email: req.body.email,
        password: Crypto.AES.encrypt(req.body.password, process.env.SECRET_KEY).toString(),
        firstName: req.body.firstName,
        surname: req.body.surname,
        username: req.body.username,
    });
    try{
        const newedUser = await nowyUser.save();
        res.status(201).json(newedUser);
    }
    catch(err){res.status(500).json(err)};
})
 
// Create a login

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne({email: req.body.email});
        if (!user) {
            return res.status(401).json("i/lub hasło jest nieprawidłowy");
        }
        

        const securedPass = Crypto.AES.decrypt( user.password, "a");
        const password = securedPass.toString(Crypto.enc.Utf8);
        console.log(password);
        if (password !== req.body.password) {
            res.status(401).json("Email i/lub hasło jest nieprawidłowy");
        }else {
            res.status(200).json(user);
        }
    } 
    catch(err) {
        res.status(500).json({message: err.message});
    }
    
});


module.exports = router

And my .env

MONGODB_URL = mongodb+srv://someInterestingWords
PORT = 5500
SEC_KEY = a

Everything works when these variables are in my code, not in .env.
I’ve tried to delete dotenv and add it again but id doesn’t change anything.
process.env.something works in index.js but it doesn’t in other files

My project file structure

Javascript works in html but won’t work in .js file

I am very new to JavaScript and have a bit of code that works when included directly in my html file, but when I try and put it into the .js file I am building for my website, it stops working.

Is the “$” being in the .js file causing the problem?

How do I re-write this code so that it can be used in my JS file?

   $('body').click(function() {
      $('div.childSection').hide();
        });
      $(".dropSection a").click(function(event) {
          var parent = $(this).parent();
          parent.toggleClass("selected");
          parent.find("div.childSection").toggle();
          parent.find("section-content").toggle();
          event.stopPropagation();
        });

How to slice part of string from the middle to the end using javascript

I have string like this:

река Марица - гр. Първомай + Maritsa - 132543 - HPoint-Water level

I want to get only Maritsa - 132543 - HPoint-Water level with javascript.

For now I get the string and console log all string, but I need to cut the cyrillic string and - before Maritsa.
The problem is that the loaded names are always different. Is there a way to delete everything before the + including it and show everything after the +

image

Why does react component only renders after ctrl + shift + R?

I have a chrome extension and it only shows up after after refreshing the page with ctrl + shift + r, but now I have a problem of whenever I click on a link that ends up refreshing the page, the extension goes away and I have to hard refresh again.

I tried using window.location.reload() but sometimes it’ll keep reloading the page non stop.
here’s the code to render:

class IconExtChrome extends React.Component<IProps, IState> {

    constructor(props) {
        super(props);
        this.state = { _isLoggedIn: false };
        this.login = this.login.bind(this);
        this.logout = this.logout.bind(this);
        this.popover = this.popover.bind(this);
        this.setAuthState = this.setAuthState.bind(this);
        this.setAuthState();
    }

    render() {
        return (
            <div className="bootsrtap-iso">
                <OverlayTrigger trigger="click" rootClose placement="bottom" overlay={this.popover()}>
                    <img src={chrome.runtime.getURL('favicon.png')} width="40" height="auto" />
                </OverlayTrigger>
            </div>
        )
    }


    popover(): OverlayChildren {
        return (
            <Popover className="bootstrap-iso">
                <Popover.Body className="p-2 d-grid text-center">
                    <PopoverHeader as="h4">{(this.state._isLoggedIn ? 'You are currenlty logged in' : 'You are currenlty logged out')}</PopoverHeader>
                    <Button className="m-auto mt-2" variant={this.state._isLoggedIn ? 'danger' : 'primary'} size="sm" onClick={this.state._isLoggedIn ? this.logout : this.login}>{this.state._isLoggedIn ? 'Logout' : 'Login'}</Button >
                </Popover.Body>
            </Popover>
        );
    }

    login() { Login(() => { this.setAuthState() }, () => { console.log("failed to login") }) }
    logout() { Logout(() => { this.setAuthState() }); }
    setAuthState() { IsLoggedIn((isLoggedIn: boolean) => { this.setState({ _isLoggedIn: isLoggedIn }); }); }
    refreshToken: () => { RefreshToken(); }
}

const GmailFactory = require("gmail-js");
const gmail = new GmailFactory.Gmail() as Gmail;

var btn = gmail.tools.add_toolbar_button('<div id="icon_placeholder"></div>', function () { }, 'temp_css').get(0)['className'];

const getElement = document.querySelectorAll('.' + btn.toString().replace(' ', '.'))[5]
var app: HTMLElement = document.createElement('div') as HTMLElement;
var pos: HTMLElement = getElement as HTMLElement;
if (pos !== null) {
    console.log('pos: ' + pos)
    pos.appendChild(app);
    ReactDOM.render(<IconExtChrome />, app);
}

Any way I could easy hard refresh the page or a proper fix for only showing up after refreshing with no cache?

How can Access the value of input text tag by it’s ID in Javascript

so i am trying to access the value of input field in html by clicking the button
this is HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <script src="index.js"></script>
</head>
<body>
    <form action="">
    <label id="stringlbl">String</label><br>
    <h4>Enter your text:</h4><input type="text" id="name" value="vikram"><br>
    <input type="submit" id="btn">
</form>
</body>
</html>

And the My Javascript Code:

const str = document.getElementById("stringlbl")
var inputE1 = document.getElementById("name").value;
const btnE1 = document.getElementById("btn")

btnE1.onclick = function (){
    document.getElementById("stringlbl").innerHTML = "String" + inputE1
}

Error message is showing in browser is :

Uncaught TypeError: Cannot read properties of null(reading 'value') at index.js:2:46

please help me

How can I send my items into this object in a automatic way? (Javascript)

I have an object inside a single array, but inside that object I get two items which is message and name

const chat = [{
    name: null,
    message: null,
}];



console.log(chat);

example:

I want to send the name Anna with the message Hi, so it should get back to me

[{ name: Anna, message: hi }]

Now I would like to send the name Bryan and with the message “How are you”, but I would like to add this without having to delete my previous object Anna

then it would stay

[
 { name: Anna, message: hi },
 { name: Bryan, message: How are you? }, 
]

I would like a new name and message object to be added every time I send a new one, without deleting the previous one

I have an independent scrolling column and need some JavaScript to force scroll to the bottom of that before the whole section scrolls

So I have a website where the top section is has a column with independent scrolling to feature vendors. I used CSS on the column to do this just using “overflow:auto;”. I would like the section to be forced to scroll to the bottom of the scrollable column no matter where your mouse is on the section across the whole page. Can anyone please help me figure out how to do this?

Link to site: https://applebrides.com/

I just have the one section with overflow:auto; which does what I want but only when your mouse is over that scrolling section.

Downloading and sending pdf document in Node through API

I am new to node, I want to download a pdf document from some another url when person hits a post request in the back-end, change the name of file and send the file back to original client where the pdf will be downloaded.
NOTE the file should not be saved in server

first there is controller file which contains following code

try {
      const get_request: any = req.body;
      const result = await printLabels(get_request,res);
      res.contentType("application/pdf");
      res.status(200).send(result);
    } catch (error) {
      const ret_data: errorResponse = await respondError(
        error,"Something Went Wrong.",
      );
      res.status(200).json(ret_data);
    }

Then after this the function printLabels is defined as

export const printLabels = async (request: any,response:any) => {
  try {
    const item_id = request.item_id;
    let doc=await fs.createReadStream(`some url with ${item_id}`);
    doc.pipe(fs.createWriteStream("Invoice_" + item_id + "_Labels.pdf"));
    return doc;
  } catch (error) {
    throw error;
  }
};

Using above code, I am getting error as no such file found. Also, I don’t have access of front end so is it possible to test the API with postman for pdf which I am doing or my approach is incorrect?

How to map each div with different width in react?

I have a weird problem. I’m mapping options for a submenu inside of a div (container for the submenu). And I set width of the DIV to be ‘100%’. However, the following submenu divs take the same width, even though they do not need it.

I have provided some screenshot to describe it better. You see the first submenu reaches max-width which is 400. And automatically, the second div has 400px width even though it clearly does not need it.

enter image description here

enter image description here

I tried using width=’fit-content’, or not assigning width ( so that it calculates it itself ). But they do not help at all, the submenu collapses completely and has like 50px width – which is unreadable.

Is there any way to achieve different width for all the submenus?

How can I resolve Error: “Uncaught (in promise): Error: Providers from the `BrowserModule` have already been loaded…”?

I am getting this error:
Error: Uncaught (in promise): Error: Providers from the BrowserModule have already been loaded. If you need access to common directives such as NgIf and NgFor, import the CommonModule instead.
Error: Providers from the BrowserModule have already been loaded. If you need access to common directives such as NgIf and NgFor, import the CommonModule instead.

Online it suggests to ensure all modules related to Browser Module are only imported once at the root. I have done that but I am still getting this error. Is there something else that could be firing this as well?

I only have 1 instance of BrowserModule at the root and common module imported in my child modules.

re-count numbers in string in array of objects of specific string when an object is deleted

I have an issue of re counting the numbers in strings. I am trying to re calculate title numbers based on it’s kindof type. e.g. When I delete Oranges 2 from [Oranges 1, Oranges 2, Oranges 3], it should become [Oranges 1, Oranges 2] i.e. I wanted to re count the numbers irrespective of it’s previous number. One can delete any i.e. 1 or 5 or last e.g. say 10

const req = [
    {id: 'z1', title:"Oranges 1"},
    {id: 'y1', title:"Apples 1"},
    // Oranges 2 deleted
    {id: 'a1', title: "Oranges 3"},
    {id: 'b1', title: "Apples 2"},
    // Apples 3 deleted
    {id: 'a3', title: "Apples 4"},
    {id: 'b2', title: "Oranges 4"},
    {id: 'b6', title: "Apples 5"},
    {id: 'c3', title: "Oranges 5"},
    {id: 'x1', title: "Apples 6"},
];

const titlesWithNoDigits = req.map(tab => {
  return { ...tab, title: (tab?.title || '').replace(/[0-9]/g, '').trim() };
});

const res = titlesWithNoDigits.reduce((obj, next) => {
        const updatedTitle = `${label} ${(titlesWithNoDigits[label] || 0) + 1}`;
    
       return {
        ...obj,
        [next.id]: updatedTitle,
      };
}, {});

The response I am looking for is:

{
        z1: 'Oranges 1',
        y1: 'Apples 1',
        // Oranges 2 deleted
        a1: 'Oranges 2',
        b1: 'Apples 2',
        // Apples 3 deleted
        a3: 'Apples 3',
        b2: 'Oranges 3',
        b6: 'Apples 4',
        c3: 'Oranges 4',
        x1: 'Apples 5',
}

I am trying javascript reduce function. Can anyone give an idea, please ?

Cannot set headers after they are sent to the client error nodejs error

When I am trying to post login data in Postman I get an error Cannot set headers after they are sent to the client.

const router = require('express').Router();
const User = require('../models/user');
const Crypto = require('crypto-js');
const { response } = require('express');
const secretKey = process.env.SECRET_KEY;
//  Create a registration

router.post('/rejestracja', async (req, res)=>{
    const nowyUser = new User({
        email: req.body.email,
        password: Crypto.AES.encrypt(req.body.password, process.env.SEC_KEY).toString(),
        firstName: req.body.firstName,
        surname: req.body.surname,
        username: req.body.username,
    });
    try{
        const newedUser = await nowyUser.save();
        res.status(201).json(newedUser);
    }
    catch(err){res.status(500).json(err)};
})
 
// Create a login

router.post('/login', async (req, res) => {
    try{
        const user = await User.findOne({email: req.body.email});
        !user && res.status(401).json("i/lub hasło jest nieprawidłowy");
        

        const securedPass = Crypto.AES.decrypt( user.password, process.env.SECRET_KEY);
        const password = securedPass.toString(Crypto.enc.Utf8);
        
        password !== req.body.password && res.status(401).json("Email i/lub hasło jest nieprawidłowy");
        
        response.status(200).json(user);
        console.log("dziala");
    } 
    catch(err) {
        res.status(500).json({message: err.message});
    }
    
});


module.exports = router

Error Scr

I’ve tried to put process.env.SEC_KEY in this file but it doesn’t work