I moved my index.html to the root through vscode, and I think I broke the code?

I’m super new at coding so please bare with me:
I was finally deploying my project, but the index.html was not in the root of my repository so I moved its location on vscode after trying other methods that weren’t working. Now, it is deployed but nothing aside from text is working now. How do I get it back?

1

I tried moving it back in the folder, just to see if I could open it in a default browser and see what I had before but it’s not showing anything there either.

Can’t get homemade dropdown to display above the rest of my components

I am working on my own health and wellness app to help me learn React Native and decided to create my own search bar to search an API for medication names as the user types in the text input. It all works fine, but when I go to use my homemade search bar the dropdown is not being displayed on top and is getting cut off by other components. I have tried to add a zIndex and elevation to the dropdown but neither seem to work. I also tried to add a lower zIndex’s to the containers holding the search bar and still nothing :/ . Any help would be greatly appreciated!

JS file of search bar component: https://docdro.id/o7XImNR

I am also testing this app using an android emulator

image of cut-off dropdown

How to fix the Cannot POST /index.html error?

The below is the example of calculator app with HTML and Javascript.

When I execute the program with nodemon, access the localhost:3000, and push the submit button, the error is shown on the browser(Google Chrome).

[nodemon] starting `node calculator.js`
Server started on port 3000.

Error Message

There is no error when executing the program, so how I can find the fixing points?

Cannot POST /index.html

Code

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1>Calculator</h1>
    <form action="/" method="post">
        <input type="text" name="n1" placeholder="First Number">
        <input type="text" name="n2" placeholder="Second Number">
        <button type="submit" name="submit">Calculate</button>
    </form>
    
</body>
</html>

calculator.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({extended: true})); //store the numbers in the forms

app.get("/", function(req, res){
   res.sendFile(__dirname + "/index.html"); //relative path
});

app.post("/", function(req, res){

    var num1 = Number(req.body.n1);
    var num2 = Number(req.body.n2);
    console.log(num1, num2); //no results shown

    var result = num1 + num2;
    res.send("The result of the calculation is " + result);
});

app.listen(3000, function(){
    console.log("Server started on port 3000.");
});

env file missing from modules

When i run my react app, i get an error saying .env file does not exist, even thought i have a .env file.

This is how the error looks


> [email protected] start
> node bin/www

node:internal/modules/cjs/loader:1093
  throw err;
  ^

Error: Cannot find module 'dotenv'
Require stack:
- C:UsersBrugerDownloadslandrup-dans-api-mainlandrup-dans-api-mainbinwww
    at Module._resolveFilename (node:internal/modules/cjs/loader:1090:15)
    at Module._load (node:internal/modules/cjs/loader:934:27)
    at Module.require (node:internal/modules/cjs/loader:1157:19)
    at require (node:internal/modules/helpers:119:18)
    at Object.<anonymous> (C:UsersBrugerDownloadslandrup-dans-api-mainlandrup-dans-api-mainbinwww:2:1)
    at Module._compile (node:internal/modules/cjs/loader:1275:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\Users\Bruger\Downloads\landrup-dans-api-main\landrup-dans-api-main\bin\www'
  ]
}

Node.js v19.8.1```

Add Count duplicate values in filtred array with …new Set

I have this array with duplicate values, i get these values from an API, the ccode below gets all the notes of maths without duplicate notes using the …new Set() method :

let notes = [];
if (props.getAllNotes()) {
    const maths = props.getAllNotes().map(item => {
        return item.subjects[0].math_note
    });
    notes = [...new Set(maths)];
    /*const counts = stars.reduce((acc, value) => ({
        ...acc,
        [value]: (acc[value] || 0) + 1
    }), {});*/
}

This is what i have in the props.getAllNotes() :

notes = [15,16,10,13,15,16,10,18,11,13,15,16,10,18,11];

And this is what i get :

notes = [15,16,10,13,18,11];

I want to add the count of each note in the final array notes like this for ex :

notes = [{10: 3}, {15, 5}...]

The commented method does it in object, i need to do it to the final array notes in which i using the …new Set() method because i am mapping through it to render some data

const counts = stars.reduce((acc, value) => ({
    ...acc,
    [value]: (acc[value] || 0) + 1
}), {});

How to resize video in React Native?

When displaying a video using the expo-av library, the video takes up the entire screen and some of its width gets cropped, as shown below:

enter image description here

Currently, here’s how the video is displayed:

function DisplayScreen({route, navigation}) {
    const video = React.useRef(null);
    const [status, setStatus] = React.useState({});

    return(
        <View style={global.vidContainer}>
            <Video
                ref={video}
                style={global.video} 
                source = {require("../assets/demos/Bridges.mp4") }
                useNativeControls
                resizeMode="contain"
                isLooping
                onPlaybackStatusUpdate={setStatus}
            />
            <View>
                <Button
                title={status.isPlaying ? 'Pause' : 'Play'}
                onPress={() =>
                    status.isPlaying ? video.current.pauseAsync() : video.current.playAsync()
                }
                />
            </View>
        </View>
    )
}

and my styles (global.js)

vidContainer: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        height: 400
    },

    video: {
        width: 400,
        height: 100,
        resizeMode: 'contain',
        flex: 1,
        alignSelf: 'flex'
    }

I’ve also tried width: window.width for styling video, however with that the video just completely does not show up. How do I go about this?

Paypay API solution Mass Pay

Is there an integration in paypal to distribute payments to different people from a web page that offers a service for product sellers? Just like Mercado Libre, regardless of the products you choose and from whom, Mercado Libre distributes the money to the corresponding sellers.

I have only tried with a single business account in my web system, integrating the API for a single seller, but I am thinking of expanding the system so that more sellers can use the page, but it gets complicated when a client wants several products from several sellers, how to distribute the money correctly?

Slack App API in Glitch / Bolt Not Getting Actions

I am new to building Slack apps, and I am stumped. I am using Glitch, Bolt, and Socket Mode. I was able to create a message block and successfully send it to users in my workspace. However, I can’t seem to receive anything.

I copied the exact code from this official tutorial:

const { App } = require('@slack/bolt');

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
  socketMode: true,
  appToken: process.env.SLACK_APP_TOKEN,
  port: process.env.PORT || 3000
});

// Listens to incoming messages that contain "hello"
app.message('hello', async ({ message, say }) => {
  console.log('said hello')
  // say() sends a message to the channel where the event was triggered
  await say(`Hey there <@${message.user}>!`);
});

(async () => {
  // Start your app
  await app.start();

  console.log('⚡️ Bolt app is running!');
})();

Here is everything I have tried/checked:

  • The app is running in Glitch console
  • The env variables are correct
  • Socket Mode is enabled
  • Enable Events is on
  • My Slack App Token has connections:write
  • Subscribe to Bot Events is on for all four message. events
  • Restarted my Slack app and Slack on my desktop
  • Typed hello at the bot in my DM with it

I initially started by trying to respond to user button clicks, and a caution symbol appeared beside the button. Getting down to basics with the above code hasn’t helped–console.log('said hello') never happens. Please help me; I’m going nuts!

Disable top level await error or set as module per file

How can I disable errors when writing standalone nodejs shell scripts?

Using ALE with VIM and a somewhat outdated eslint (v7.32.0). (I am going to install new OS and for now I’m somewhat stuck with that version do to a myriad of version conflicts and a general mess when it comes to node.)

Anyhow: I often write small scripts for testing purposes or as stand-alone scripts. I.e. they do not have a .eslintrc – but merely rely on the global defaults.

As I can use await at top-level I wonder how I can get rid of the error:

Parsing error: Cannot use keyword ‘await’ outside an async function

Can I use some inline /* eslint ... */ rule to fix this? Something like:

/* eslint sourceType: module */
/* eslint-disable await-oustide-async */

I use .mjs extension for it to run with node.

Environment Info:

Node version: v16.16.0
npm version: v8.11.0
Local ESLint version: v7.32.0 (Currently used)
Global ESLint version: Not found

Have searched the web for a while, but it either is a unique issue, which I doubt, or that I use the wrong terms.

Dynamically loading react component from prop value

I’m trying to load a react component with several subcomponents (that themselves have props) dynamically, similar to the solution suggested here.

I’ve built a Base component that takes a string value, and then the Base component looks up that string value to instantiate the sub-components that need to be rendered. At the moment I’ve only added a single component for “Users” to illustrate the problem.

However, I keep running into an error saying that

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

I don’t know what I’m doing wrong, I think everything is being imported correctly and webstorm doesn’t show any issues with what I’ve done, until I load the page.

I’ve built a stackblitz to show the problem. It seems like this route is very straightforward, but I’m missing something and I don’t see what it is.

Edit contents of front-end HTML file based on value from express-session

I am currently trying to build a login page for my web application using express-session. I have everything working as far as confirming a valid login.

Once a valid login is confirmed, I run the following code within the app.post() method.

request.session.loggedIn = true
request.session.username = data[0].account_user
response.redirect('/')

The redirect takes me back to the home page. How can I then now check the value of those variables, and edit what the user sees on the front-end?

For example if nobody is logged in, I want it to display login/signup buttons. If they are logged in, I want to hide those and display their username.

Javascript Click Event Listener not firing but has been added to button

Hoping someone can help me here because I can’t figure out what’s going on

I’m trying to add an event listener to this Shopify Add to Cart button, in Firefox I can see that the ‘click’ event is being added to button, however the code isn’t being fired

Code I’m using and have used many times for other small scripts

Update – Seems like it’s caused because of the type="submit" but that’s needed, so I’m not sure how to work around it

const addToCartButton = document.querySelector('[data-add-to-cart]');

addToCartButton.addEventListener("click", () => {
  console.log('clicked')
}); 

enter image description here

Is there a way that I can make my code detect the changes made in local storage before reloading?

I tried to check if a string value displays on the screen once a button is clicked.It works after reloading the page and then it stops same as before reloading it

let ids1 = document.getElementById('ids')
let ids2 = document.getElementById('ids2')

function saveit(){
    localStorage.setItem('store', ids1.value)
    localStorage.setItem('store2', ids2.value)
}

//button to save in local storage once is clicked on each ids1 item
let buttonAddSt = Array.from(div).forEach(e =>{ 
let inputButton = document.createElement('button')
inputButton.innerHTML = 'add'
inputButton.addEventListener('click', saveit )

    e.appendChild(inputButton) 
})

//button to display info once storage show has value/keys
let buttonTask = document.getElementsByClassName('create')

let local = localStorage.getItem('store')
let local2 = localStorage.getItem('store2')


let paro = document.createElement('p')
 paro.innerHTML = local

let newd = document.getElementsByClassName('newd')

//nested if statement to point out specific info missing 
if(local !== null ){
    if(local2 !== null){      
        buttonTask[0].addEventListener('click', fire)
    }else{
        buttonTask[0].addEventListener('click', () => {
            alert('date is required')
        })
    }

} else {
    buttonTask[0].addEventListener('click', () => {
        alert('description is required')
    })
    
}  

by clicking on buttonAddSt data is saved so I expected that clicking on buttonTask that will be display but it is like data in local storage key/values are not detected prior to reload even though I can see it. It works after reloading because data is already in localstorage but prior to that if I what to start on an empty input field I do if(local == null ) and it stops displaying the info after refresh, it is like Im in a loop

User’s username not appearing on React navigation bar

I am using React to create a Navbar component for your website. The Navbar should display the user’s username, the user is logged in, and provide links to various pages on the website. I am using localStorage to store the user’s data, and axios to make API requests. However, i am encountering an issue where the user’s username is not appearing on the Navbar.

function NavbarScroll() {
const navigate = useNavigate();
const [user, setUser] = useState(null);

function handleLogout() {

axios.post(${API_URL}/logout)
.then(response => {
Remove the user data from localStorage and set user state to null
localStorage.removeItem(‘user’);
setUser(null);

Navigate to the home page after logging out
navigate(‘/’);
})
.catch(error => {
console.error(error);
});
}

useEffect(() => {
const userData = JSON.parse(localStorage.getItem(‘user’));
console.log(‘userData:’, userData); // add this line to verify the userData value
if (userData !== null) {
setUser(userData);
}
console.log(‘user:’, user);
[]);

return (

<Nav.Link>{user && Welcome, {user.username}}</Nav.Link>

);}export default NavbarScroll;