Favicon and pictures not getting served by Flask to a React app

I have a Flask server that is set up like this

app = Flask(__name__,
            static_folder="dist/assets",
            static_url_path='/assets',
            template_folder="dist")


CORS(app)
socketio = SocketIO(app, cors_allowed_origins='*')

My Flask directory looks like this

Flask
|- Classes
|- dist
|- log
|- main.py
|- Settings

And the dist looks like this

dist
|- assets
|- index.html
|- MyFavicon.png
|- vite.svg

In flask I have a basic index route

@app.route('/')
def index():
    return render_template("index.html")

The index route loads, the problem is the assets and the favicon do not load

From the browser I get errors like this

GET
http://localhost:5000/MyFavicon.png
[HTTP/1.1 404 NOT FOUND 0ms]

And this is what the index.html looks like

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <link rel="icon" href="/MyFavicon.png" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Monitor</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

Does anyone know if the problem is the way Flask is trying to serve the static files or is it the way I am referencing things on React side of things?

EDIT:

Also this is the directory in React

React
| - public
| - src
    | - assets

Where the favicon is in public, and the rest of my pictures are in assets

Order of processing microtasks in JavaScript

I’m solving an event loop problem in Javascript and I can’t figure out why the output order is 2, 1, and not 1, 2.

f1();

Promise.resolve().then(() => {
  console.log(2);
});

async function f2() {
  return new Promise((resolve) => {
    resolve();
  });
}

async function f1() {
  f2().then(() => {
    console.log(1);
  });
}

Let me tell you my reasoning:

  1. As far as I understand, the first task in call stask will be f1. This function is asynchronous and returns a promise.

  2. f1 is being executed.

  3. Inside f1 there is a call to f2, which returns a promise and immediately resolves it. Therefore, a callback in “then” containing console.log(1) is added to the microtask queue.

  4. There is one more task left on the call stack – Promise.resolve(). Here a callback in “then” containing console.log(2) also ends up in the microtask queue.

  5. The call stack is empty, which means the event loop executes tasks from the microtask queue in order – 1, 2.

At some of these steps I was definitely mistaken in my reasoning. I will be very grateful if anyone helps me!)

Select Element with multiple attribute not showing all values using FormData object

I have a form that has select elements that display dynamically. The user can input the number of horses they have trimmed (input element). Depending on the number of horses they inputted, that many select elements will pop up with the list of the clients horses. Upon selecting the horse’s name, another select element is displayed with the different options of services. In this case it is “Trim”, “Front Shoes”, “Full Shoes”, “Reset Front Shoes”, “Reset Full Shoes”. If the user selects on anything other than “Trim” another select box will be displayed with “Accessories”. The accessories select box is set to multiple to allow the user to select more than one accessory.

My Problem
I’m using JavaScript and the FormData object to catch all information from the form. But I have found that FormData is not returning all the selected options/values from the accessories. So I had found this code and implemented it:

const atf = document.getElementById('add_trimming_form');
const formData = new FormData(atf);
const selectElements = atf.querySelectorAll('select[id^=accessories_]');    

for (const select of selectElements) {
    const values = Array.from(select.selectedOptions, option => option.value);
    const name = select.getAttribute('name');

    for (const value of values) {
        formData.append(name, value);
    }
}

const data = Object.fromEntries(formData);
console.log(data);

According to the documentation from mdm web_docs:

As with regular form data, you can append multiple values with the same name:
formData.append(“userpic”, myFileInput.files[0], “chris1.jpg”);
formData.append(“userpic”, myFileInput.files[1], “chris2.jpg”);

When I submit the form, and do the console.log(data), this is the data I’m getting:

accessories_1: “wedges:15.00”
accessories_2: “pads:15.00”
app_time: “09:00:00”
horse_list_1: “U2FsdCB0byBlbmNyeXB0IHRoZSBDbGllbnQgSUQ6a25lZSBrbm9ja2Vy”
horse_list_2: “U2FsdCB0byBlbmNyeXB0IHRoZSBDbGllbnQgSUQ6bW9sbHk%3D”
next_trim_date: “2024-01-18”
num_horses: “2”
payment: “260”
payment_cost_1: “reset_front_shoes_urethane:95.00”
payment_cost_2: “front_shoes_urethane:120.00”
trim_date: “2023-12-14”

the “accessories_1” should have both the “pads:15.00” AND the “wedges:15.00”.

I cannot find what I am missing or what I’m doing wrong. Can someone please point me in the right direction?

Express: Access path param inside router.use()

Consider the following setup.

var router = require('express').Router();

function someMiddleware(id) {
  return (req, res, next) => {
    // do something with id
    next();
  }
}

router.use('/:pathId', someMiddleware(pathId) /*, add more middleware */); // doesn't work

How can I access the pathId in router.use? Is it even possible or do I need a different setup?

The reason why I don’t want to access it via req.params.pathId inside of someMiddleware is that I want the middleware to be agnostic of the actual parameter name, so I can use it in different setups.

I cannot retrieve the data even though it is stored in the database

I created a project with mern stack, and when I try to comment on the post from the client, the comment does not appear, even though it shows me that the comment was completed successfully, and the comment is saved in the database.

In one of my attempts, I was able to make comments print on the console, but I cannot make them appear on the page

Comments should appear in the post page

PostPage.jsx:

    const { pid } = useParams();

  const currentPost = posts[0];
  useEffect(() => {
    const getPost = async () => {
      setPosts([]);
      try {
        const res = await fetch(`/api/posts/${pid}`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        setPosts([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getPost();
  }, [pid, setPosts, showToast]);

  useEffect(() => {
    const getComment = async () => {
      setComments([]);
      try {
        const res = await fetch(`/api/comments/${pid}/comments`);
        const data = await res.json();
        if(data.error) {
          showToast("Error", data.error, "error");
          return;
        }
        console.log([data])
        setComments([data]);
      } catch (error) {
        showToast("Error", error.message, "error");
      }
    }
    getComment();
  }, [pid, setComments, showToast]);

return (
  ...page codes

  <Flex>
  
{comments?.length >= 0 && comments?.map((comment) => {
  return <Comment 
  key={comment?._id} 
  comment={comment} 
  lastComment={comment?._id === comments[comments?.length - 1]._id}
  />
})}
</Flex>

)

comment.jsx:

import { Avatar, Divider, Flex, Text } from "@chakra-ui/react";


const Comment = ({ comment, lastComment }) => {
  return (
    <>
    <Flex gap={4} py={2} my={2} w={"full"}>
        <Avatar src={comment.userProfilePic} size={"sm"}/>
        <Flex gap={1} w={"full"} flexDirection={"column"}>
            <Flex w={"full"} justifyContent={"space-between"} alignItems={"center"}>
                <Text fontSize={"sm"} fontWeight={"bold"}>
                    {comment.username}
                </Text>
                
            </Flex>
            <Text>{comment.comment}</Text>
        </Flex>
    </Flex>
    {!lastComment ? <Divider /> : null}
    </>
  )
}

export default Comment

commentController.js

const getComments = async (req, res) => {
        const id = req.params;
        try {
            if(id) {
            const comments = await Comment.find({ postId: id }).sort({ createdAt: -1 })
            res.json(comments);
            } else {
                res.status(404).json({ message: "Comments not found!" })
            }
        } catch (error) {
            
        }
    }

commentModel.js

import mongoose from "mongoose";
const ObjectId = mongoose.Types.ObjectId;

const commentSchema = mongoose.Schema({
    postId: {
    type: ObjectId,
    ref: "Post",
    required: true,
    },
    comment: {
        type: String,
        required: true,
    },
    replies: [{
        reply: {
            type: String,
            required: true,
        },
        username: {
            type: String,
            required: true,
        },
        commentId: {
            type: ObjectId,
            required: true,
        },
    }],
    username: {
        type: String,
        required: true,
    }
}, {
    timestamps: true
})

const Comment = mongoose.model('Comment', commentSchema);

export default Comment;

How to Configure Prettier/ESLint to Keep Space Between Function Name and Parentheses? VS Code

I’m using Visual Studio Code for a JavaScript project and facing a formatting challenge with Prettier, which I’m using in conjunction with ESLint. My preference is to maintain a space between the function name and the opening parenthesis. However, after formatting with Prettier, this space is being removed.

Desired Formatting:

function name (args) {
  // function body
}

Current Formatting by Prettier:

function name(args) {
  // function body
}

So far, I have tried adding “javascript.format.insertSpaceBeforeFunctionParenthesis”: true to my settings.json file in VS Code, but this hasn’t resolved the issue. I am looking for a way to configure either Prettier, ESLint, or VS Code to achieve this specific formatting style.

Is there a configuration option in Prettier, ESLint, or a VS Code setting that can enforce this space? Any guidance on adjusting settings or rules to preserve this space consistently across my codebase would be greatly appreciated.

Insert data into database using react and node.js error

I have a problem. when I try to insert data into the database it works and usually page does not refresh, but when I try to upload images too, images upload but the data does not insert into the database, and the page refreshes (It is not normal):

react.js:
https://github.com/worldremo/Top_Gardering/blob/main/client/src/views/Home.jsx

node.js/express.js
https://github.com/worldremo/Top_Gardering/blob/main/server/index.js

Nextjs api not working on vercel version 18

I have created this simple api when the page loads:

const GetResponse = async () => {
      const res = await fetch("/api/createAcc/check", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify("hello"),
      });
      if (!res.ok) {
        const errorMessage = await res.json();
        console.error("Error if:", errorMessage.error);
        return;
      }
    };

and here is the recieving end:

export default async function Check(req, res) {
  try {
    res.json({ message: "Success" });
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: "Internal server error" });
  }
}

but the server respons with error. It works locally but crashes on vercel.

Server is showing 404 error. resource not found

I tried to build a personal website following a template and the website worked perfectly locally. However, after I deployed it to GitHub Pages, I can only see a blank page. I checked the Javascript console and here is the error message:
Server responded wth an error of 404. resource not found
does anyone have a clue why
here is my rep: https://github.com/Rudra2122/3DPortfolio
here is my blank page repo: https://rudra2122.github.io/3DPortfolio/

i think js is the problem and not loading
however if i run it using “npm run dev” it is running locally on vs code

How to do a NavBar Active with the slides?

Okk, this is a bit strange, but I need to do this.

So I have a NavBar with the “Home”, “Company”, etc…
And I have a second Navbar who I want to work in set with Sliders.
So the Ideia was:

I have the first slide on show (imagine “Packing”) and I want the second navbar active on “Packing”. They are eight. Eight sliders and eight href on the navbar.

This is possible? I do a search but I don’t find anything about this…

I leave the code.

I what expecting the first slide on show (imagine “Packing”) and I want the second navbar active on “Packing”. They are eight. Eight sliders and eight href on the navbar.

Advanced Movie filter problem with react and firebase

I’m doing movie a movie site something like here https://www.justwatch.com/us?genres=scf&rating_imdb=5.1

“All, Movies, TV Shows” is a the main panel and genres option is a secondary panel and each time I click either All, Movies or Tv Shows it fetches data like it supposed to and then genre filter works on top of that also.

But the problem is when lets say I select “Romance” while main panel is selected on “Movies” and then I click “TV Shows” to replace “Movies” it fetches everything again and doesn’t categorize Romance TV shows, it just shows all TV Shows and then i have click on “Romance” genre again:

i’m maping genre data from here:

const genreList = [
    {
    id: 1,
    name:'All',
    active: true,
    },

    {
    id: 2,
    name:'Thriller',
    active: false,
    },

    {
    id: 3,
    name:'Romance',
    active: false,
    },

    {
    id: 4,
    name:'Comedy',
    active: false,
    },

    {
    id: 5,
    name: 'Drama',
    active: false,
    },
]

pulling data from firestore:

const NavigateMovies = (props) => {
    const [data, setData] = useState([])
    const [movies, setMovies] = useState([])
    const [genres, setGenres] = useState(genreList)
    const [videoType, setVideoType] = useState("All")

    async function fetchDataFromFirestore() {
        const data = []
        switch (videoType) {
            case "All":
                const querySnapshot1 = await getDocs(db.collection("movies"))
                const querySnapshot2 = await getDocs(db.collection("tvshows"))
                querySnapshot1.forEach((doc) => {
                data.push({id: doc.id, ...doc.data()})
                })
                querySnapshot2.forEach((doc) => {
                data.push({id: doc.id, ...doc.data()})
                })
                break;
                
            case "Movies":
                const querySnapshot3 = await getDocs(db.collection("movies"))
                querySnapshot3.forEach((doc) => {
                data.push({id: doc.id, ...doc.data()})
                })
                break;

            case "Tv Shows":
                const querySnapshot4 = await getDocs(db.collection("tvshows"))
                querySnapshot4.forEach((doc) => {
                data.push({id: doc.id, ...doc.data()})
                })
                break;
        }
        return data       
    }
    
    useEffect(() => {
        async function fetchData() {
            const data = await fetchDataFromFirestore()
            setData(data)
            }
        fetchData()
    },[videoType])

    useEffect(() => {
        setMovies(data);
    }, [data])

then i’m doing this:

const handleFilterMovies = category => {
setGenres(
genres.map(genre => {
genre.active = false;
if(genre.name === category){
genre.active = true;
}
return genre;
})
)

    if (category ==='All') {
        setMovies(data)
        return;
    }

    const filteredMovies = data.filter(movie => movie.genre === category)
    setMovies(filteredMovies)
};

return (
<div className="movie-nav-container">
    <div className="categories">
        <button onClick={() => {setVideoType("All"); }}>All</button>
        <button onClick={() => {setVideoType("Movies"); }}>Movies</button>
        <button onClick={() => {setVideoType("Tv Shows"); }}>TV Shows</button>
        <ul>
            {
                
            genres.map(genre => (
                <li key={genre.id} className={`${genre.active ? 'active': undefined}`} onClick={()=>{handleFilterMovies(genre.name)}}>{genre.name}</li>
            ))
            }
        </ul>
    </div> 
    <div className="movies">
        {
        movies && movies.length >0 && movies.map(movie => (
        <div className='wrap'><img src={movie.imageCoverLink} alt="" /></div>
        ))
        }
    </div> 
</div>)

}

I’ve tried all the combinations but it didn’t seem to work

Recursive render with array of objects inside React Context

I have a code, which consists of a Markdown editor that parses the text and extracts information about Headers. I plan to build a menu with the headers and when clicked jump to the header inside the editor. Something like a Table of Contents.

const Editor = ({ initValue, style, onChange = () => {} }: EditorProps) => {
  const [value, setValue] = useState<string>(initValue);
  const { setHeaderNodes } = useHeaderNavigation();

  const changeHandler = (text: string) => {
    setValue(text);
    onChange(text);
  };
  const ast = parse(value);

  const headers: HeaderNavigationNode[] = useMemo(() => {
    return ast.filter(isHeaderNode).map(node => {
      const { content, loc: { start: { line } } } = node;
      return { content, line };
    });
  }, [ast]);

  useEffect(() => {
    setHeaderNodes(headers);
  }, [headers]);

  console.log(JSON.stringify(headers, null, 4));
  ...
};

// Context.ts

import { createContext, useContext } from 'react';

export interface HeaderNavigationNode {
  content: string;
  line: number;
}

export interface Context {
  headerNodes: HeaderNavigationNode[];
  setHeaderNodes: (nodes: HeaderNavigationNode[]) => void;
}

export const NavigationContext = createContext<Context>(null)

export const useHeaderNavigation = () => useContext(NavigationContext);

// App.tsx
export default function App() {
  const [headerNodes, setHeaderNodes] = useState<HeaderNavigationNode[]>([]);
  return (
    <NavigationContext.Provider value={{ headerNodes, setHeaderNodes }}>
      <Editor
        initValue={`# HEADER 1

```
function hello(name) {
   return `hello ${name}`;
}
````} />
    </NavigationContext.Provider>
  );
}

The problem is that it this creates infinite loop of rerender. I’ve tried to add useMemo for the headers but this didn’t fix the issue. I think that I add React.memo for the editor. But this sounds like a hack the same as useMemo in my code.

What should I do to make the array inside Context doesn’t rerender everything in a loop?

I know that ast is new array/object each time the components re-render so I need some kind of deep checking if the array of HeaderNodes is the same as before when calling setHeaderNodes but I’m not sure how to do that.

Can you select a custom element by the is: attribute?

Is there a selector for a custom element, can you use the is: attribute ?

querySelector(div[is:'custom-element']) ?

Also, the is: attribute is missing from the element if you create it using the new keywork or using document.createElement('div', {is: 'custom-element})

class CustomDiv extends HTMLDivElement {
  constructor() { super() }
}
customElements.define('custom-element', CustomDiv, {extends: 'div'})

// const newElement = new CustomDiv()
// document.querySelector('body').append(newElement)
div {
  height: 40px;
  width: 40px;
  background: black;
  border-radius: 50%;
}
<div is='custom-element'></div>

Blue box when clicking on Javascript element on mobile devices

I created code for some flipping images with HTML, CSS, and some Javascript. The code works perfectly, however I’m facing an aesthetic issue when I’m accessing the live site on mobile devices: When you tap on one of the images, a blue box shortly appears around the image.

Strangely, the issue only appears on the live site (Edit: See picture below for reference) and not on the Codepen Demo (some minor aspects of the css were changed on the live site, but nothing that should influence this behavior). This makes me think it might have something to do with the other CSS/Javascript generated by either WordPress or WP Bakery.

Is there something that can be done to circumvent the blue box from appearing?

`<div class="image-wrapper">
<div class="flip-image--holder">
<div class="flip-image" id="diana--front" onclick="flipImage(this)">
<button class="flip-button">
<i class="fa-solid fa-repeat" style="color: #99cc00;"></i>
</button>
</div>
<div class="flip-image flip-image--back" id="diana--back" onclick="flipImage(this)">
<button class="flip-button">
<i class="fa-solid fa-repeat" style="color: #99cc00;"></i>
</button>
</div>
</div>
</div>
<script>
function flipImage(button) {
  var flipImageHolder = button.parentElement;
  flipImageHolder.classList.toggle("flipped");
}
</script>`

Honestly, I wouldn’t know where to start solving this issue. My best guess is that it’s something css-related.

I’m using Chrome and a phone with Android 14.

The issue looks like this: The issue looks like this.