How to resolve ‘these 2 errors’ in a web project with JavaScript, HTML, and AI?

I’m working on a project where I have an HTML file with embedded JavaScript code. The JavaScript code is responsible for handling user input, making API calls, and displaying the results. However, I’m encountering an issue with the code execution.

When I load the HTML file in a browser, the console displays an error message: “Uncaught ReferenceError: require is not defined” pointing to line 1 of my script.js file. I understand that the require() function is typically used in Node.js for module imports, but in this case, I’m not using Node.js.

I’ve tried removing the require() statements from the code, as well as including the Axios library directly in the HTML file using the tag. However, I still encounter the same error.

I’ve also verified that the paths to the JavaScript and CSS files are correct in the HTML file, so that doesn’t seem to be the issue.

I’m using the latest version of Chrome as my browser, and my HTML file is being served from a local web server.

Any insights or suggestions on how to resolve this issue would be greatly appreciated. Thank you in advance for your help!

NEXTJS/NEXTJS13 Contact Form error – “API resolved without sending a response for /api/send-mail, this may result in stalled requests”

I am building a contact form in Nextjs . Basically I was trying to run code that I got from DEV –Link–https://dev.to/wpickeral/building-a-contact-form-with-nextjs-and-nodemailer-4emp — .But now The error is coming “API resolved without sending a response for /api/send-mail, this may result in stalled requests.”
This is my file structure< I don’t know if my api route is correct or not

Below is my send-mail.js inside api

const nodemailer = require('nodemailer');

export default async function handler(req, res) {
  const message = {
    from: req.body.name,
    to: process.env.GMAIL_EMAIL_ADDRESS,
    email: req.body.email,
    text: req.body.message,
    html: `<p>${req.body.message}</p>`,
  };

  let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: process.env.GMAIL_EMAIL_ADDRESS,
      pass: process.env.GMAIL_APP_PASSWORD,
    },
  });

  if (req.method === 'POST') {
    transporter.sendMail(message, (err, info) => {

      if (err) {
        res.status(404).json({
            error: `Connection refused at ${err.address}`
        });
      } else {
        res.status(250).json({
            success: `Message delivered to ${info.accepted}`
        });
      }
    });
  }
}

This is sendEmail.js

import axios from 'axios';

const sendEmail = async (name, email, message) => {
  return axios({
    method: 'post',
    url: '/api/send-mail',
    data: {
      name: name,
      email: email,
      message: message,
    },
  });
};

export default sendEmail;

this is the error im getting

Initially I was trying with Next13 route handling , but couldn’t resolve the api path and was getting error. I’m kinda new at this so has not much of an idea. Then I checked a blog where it said that pages/api should also work like before, so i created pages folder and inside it created api

Why node.js execute my function before connect mongodb

This pic is from firebase log it show start connect then it execute before connect

`I'm try to use route after connect mongodb`

// Connect Database
connectMongodb(app)
  .then(() => {
    // Routes can be set up after the MongoDB connection is established
    app.use(require('./routes'));

    // Firebase Cloud Functions endpoint
    exports.app = functions.https.onRequest(app);
  })
  .catch((error) => {
    console.error("MongoDB connection failed:", error);
    // Handle the error accordingly
  });

Why isn’t data from Route Handlers updated?

I was testing out the new Route Handlers in next next 13.4.4 when I stumbled upon a problem. The data doesn’t update at all, so if I change the text of the NextResponse the data shown on app/page.js remains the same. Here is the code:

async function getTodos() {
  const res = await fetch('http://localhost:3000/api');

  if (!res.ok) {
    throw new Error("Couldn't fetch data");
  };

  return res.json();
}

export default async function Home() {
  const todos = await getTodos();

  return (
    <main className='bg-neutral-900 text-white min-h-screen'>
      <div className="container mx-auto">
        <h1>Todo App</h1>
        <pre>
          { JSON.stringify(todos, null, 2) }
        </pre>
      </div>
    </main>
  )
}


// api/route.js
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({ message: "Hello 1"})
}

Here the app/page.js shows Hello 1 which is exactly what I want, but when I changed the /api/route.js text to ‘Hello 2’, the text on app/page.js still shows Hello 1. I tested the API by going to http://localhost:3000/api and there it shows Hello 2. I also tested it by using the VS Code extension Thunder Client which showed again Hello 2. However app/page.js still isn’t working as expected. Can someone tell me how to fix this problem. Thanks!

Using p5.js, how can I stop infinite looping?

I am drawing a pizza and wanted to put toppings on it using p5.js, but when I click the checkbox to draw, the circles won’t stop looping. Is there a way to stop it from creating circles over and over again?

Checkbox html:

<div id="toppingContainer" class="checkbox-container">Choose some toppings!<br>
  <input type="checkbox" name="checkbox" value="oneC" id="checkbox1" />
  <label for="checkbox1">Pepperoni</label><br>
  <input type="checkbox" name="checkbox" value="twoC" id="checkbox2" />
  <label for="checkbox2">Cheese</label><br>
  <input type="checkbox" name="checkbox" value="threeC" id="checkbox3" />
  <label for="checkbox3">Musrooms</label><br>
  <input type="checkbox" name="checkbox" value="fourC" id="checkbox4" />
  <label for="checkbox4">Olives</label><br>
  <input type="checkbox" name="checkbox" value="fiveC" id="checkbox5" />
  <label for="checkbox5">Pineapple</label>
</div>

Javascript:

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var button3 = document.getElementById("button3");
var checkbox1 = document.getElementById("checkbox1");
var checkbox2 = document.getElementById("checkbox2");
var checkbox3 = document.getElementById("checkbox3");
var checkbox4 = document.getElementById("checkbox4");
var checkbox5 = document.getElementById("checkbox5");

function draw() {
  background(225, 0, 0);
  if (button1.checked) {
    fill(227, 217, 202);
    circle(200, 200, 100);

    if (checkbox1.checked) {
      fill(25, 0, 0);
      for (let i = 0; i < 600; i++) {
        push();
        randAng = random(0, 2 * PI);
        distFromCenter = random(0, 40);
        offsetX = distFromCenter * cos(randAng);
        offsetY = distFromCenter * sin(randAng);
        x = 200 + offsetX;
        y = 200 + offsetY;
        translate(x, y);
        rotate(random(0, 2 * PI));
        strokeWeight(0);
        circle(0, 0, 10);
        pop();
      }
    }
  }

  if (button2.checked) {
    fill(227, 217, 202);
    circle(200, 200, 200);
  }

  if (button3.checked) {
    fill(227, 217, 202);
    circle(200, 200, 300);
  }
}

Thank you!

Nouislider slider not showing up in the webpack project

Nouislider slider not showing up in the webpack project

Simply trying to add a slider and be able to just call it and do custom config for a situation, i don’t see any errors popping up not sure what am i doing wrong. Slider class is in another .js file made only for it.

js script for the slider

rangeSlider.js

import * as noUiSlider from 'nouislider';
import 'nouislider/dist/nouislider.css';
export default class RangeSlider {

    constructor(selector = "[data-js-rangeSlider]", config = { start: [ 0, 100 ], range: { min: 0, max: 100 } }) {
        this.node = document.querySelector(selector);
        if(this.node) {
            this.slider = new noUiSlider.create(this.node, config);
        }
    }
}

webpack entry file
index.js

import RangeSlider from "./js/rangeSlider.js";
const rangeSL = new RangeSlider(document.getElementById("rangeSlider"),{ start: [ 0, 100 ], range: { min: 0, max: 100 } });

html file where everything called

index.html

<body>
    <h1>
        Slider Test
    </h1>
    <div class="rangeSlider rangeSlider--isDark" data-js-rangeSlider>
        <div class="rangeSlider__inner"></div>
    </div>
</body>

Express API calls suddenly returning HTML page page instead of JSON results from database

I have been working on this ReactJS app with an Express.js and MongoDB backend for several months. I last worked on it in February of 2023 and everything, both front and back end, was working as intended when I left it.

Originally once the user entered their details and clicked the login button it would attempt to log the user in with credentials from the database and update the page or show a message depending on whether the credentials were found or not.

Now when I start the app it displays the login page as intended, but once the user clicks the login button I get this error.

Error produced from login request

I examined the login API call in Postman and got this message indicating that the request was failing

enter image description here

I tried testing another API call in Postman to determine whether it was just this request that was failing or others too. My database has a list of job objects that are meant to be retrieved using the following API call http://localhost:3000/jobs .

This however returns index.html , the default ReactJS page, from /frontend/public for some reason instead of the list of jobs from the database in JSON format. This causes the app to break as it is expecting a JSON response and instead receives raw HTML.

This leads me to believe that my Express and MongoDB backend is now not communicating with my React frontend for some reason. This has never been a problem before now and I have not made any changes to cause this.

Any advice on how to approach fixing this would be greatly appreciated. I can provide any additional information if it might help find an answer.

Symfony / Vite: Vue 3 Uncaught ReferenceError: exports is not defined

I am currently working on a Symfony 3 Application with Vite and Vue3 together with TypeScript.

I replaced Symfonys Webpack Encore with the Vite Buildtool using this plugin here:

https://github.com/lhapaipai/vite-bundle

I followed the migration guide initially and it worked before.

folder

I have an assets folder, that contains my components. Everything Vue related lies under assets/vue. My App.ts contains the needed code for my components and App.vue. This is used by Vite. The bundle then let me allow to include the compiled js into my twig files like so:

{% block stylesheets %}
    {{ vite_entry_link_tags('app') }}
{% endblock %}

{% block javascripts %}
    {{ vite_entry_script_tags('app') }}
{% endblock %}

To start my application, I need to run npm run dev (vite dev) and symfony serve (symfony server start).

My issue is: My Vue Application is not rendering anymore, Vue Devtools is also not recognizing. I can’t see my components, when I open up localhost:8000/vue.

My console displays me this error message:

app.js:8 Uncaught ReferenceError: exports is not defined
    at app.js:8:23
(anonymous) @ app.js:8

console

Why is this happening? What did I miss – I did not encounter this issue before. Below are my setup files.

I don’t get any error for running vite dev / npm run dev.

My app.vue

<script setup lang="ts">
import BaseLayout from "./layout/BaseLayout.vue";
import StickyBanner from "./patterns/StickyBanner.vue";
import ImageSlider from "./components/image-slider.vue";
import BottomMenu from "./components/bottom-menu.vue";
import NavigationBar from "./components/navigation-bar.vue";
import MasonryGallery from "./components/masonry-gallery.vue";
</script>
<template>
  <BaseLayout>
    <template #header>
      <StickyBanner />
      <NavigationBar />
      <h1>Header</h1>
    </template>
    <template #main>
      <ImageSlider />
      <MasonryGallery />
    </template>
    <template #footer>
      <BottomMenu />
      <h1>Footer</h1>
    </template>
    <slot/>
  </BaseLayout>
</template>
<style lang="scss" scoped></style>

My app.ts

/*
 * Welcome to your app's main TS file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you import will output into a single css file (app.css in this case)
import './styles/app.css';

// start the Stimulus application
import './bootstrap';
import 'flowbite';

import {createApp} from "vue";
import App from "./vue/App.vue";
import ModeSwitcher from "./vue/patterns/ModeSwitcher.vue";
import ImageSlider from "./vue/components/image-slider.vue";
import StickyBanner from "./vue/patterns/StickyBanner.vue";
import ServiceInfo from "./vue/components/service-info.vue";

const app = createApp({});

app.component('App', App);
app.component('ModeSwitcher', ModeSwitcher);
app.component('ImageSlider', ImageSlider);
app.component('StickyBanner', StickyBanner);
app.component('ServiceInfo', ServiceInfo);

app.mount('#app');

vite.config.ts

import { defineConfig } from "vite";
import symfonyPlugin from "vite-plugin-symfony";
import vue from "@vitejs/plugin-vue";
/* if you're using React */
// import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        /* react(), // if you're using React */
        symfonyPlugin(),
        vue(), // write this
    ],
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        }
    },
    base: '/build/',
    build: {
        outDir: './public/build',
        rollupOptions: {
            input: {
                app: "./assets/app.ts",
                /* you can also provide css files to prevent FOUC */
                styles: "./assets/styles/app.css"
            },
        }
    },
});

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
}

index.html.twig

{% extends 'base.html.twig' %}

{% block title %}Hello VueController!{% endblock %}

{% block body %}
    Test
<div>
    <div id="app">
        <app></app>
    </div>
</div>
{% endblock %}

base.html.twig

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}Welcome!{% endblock %}</title>
    <link rel="icon"
          href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
    {# Run `composer require symfony/webpack-encore-bundle` to start using Symfony UX #}
    {% block stylesheets %}
        {{ vite_entry_link_tags('app') }}
    {% endblock %}

    {% block javascripts %}
        {{ vite_entry_script_tags('app') }}
    {% endblock %}
    <script>
        // On page load or when changing themes, best to add inline in `head` to avoid FOUC
        if (localStorage.getItem('color-theme') === 'dark' || (!('color-theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            console.log('dark')
        } else {
            document.documentElement.classList.remove('dark')
            console.log('light')
        }
    </script>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>

package.json

{
  "devDependencies": {
    "autoprefixer": "^10.4.14",
    "core-js": "^3.23.0",
    "postcss": "^8.4.21",
    "postcss-loader": "^7.1.0",
    "regenerator-runtime": "^0.13.9",
    "tailwindcss": "^3.3.1",
    "ts-loader": "^9.4.2",
    "unplugin-vue-components": "^0.24.1",
    "vue": "^3.0",
    "vue-loader": "^17.0.1"
  },
  "license": "UNLICENSED",
  "private": true,
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "@headlessui/vue": "^1.7.12",
    "@vitejs/plugin-vue": "^4.1.0",
    "flowbite": "^1.6.5",
    "sass": "^1.62.0",
    "vite": "^4.2.1",
    "vite-plugin-symfony": "^0.7.6"
  },
  "type": "module"
}

How to access name of file in FileList object in react?

I’m trying to upload files and then send the filepath to an API in the backend to store into a database, but I’m having issues retrieving the filename from the FileList object that is created.

I have this code:

const RawForm = () => {
        const [filepath, setFilepath] = useState([])

        const handleUpload = (event) => {
               setFilepath([...filepath, event.target.files])
        }

        const handleSubmit = async (e) => {
               e.preventDefault()
               console.log(filepath)
               for (const file in filepath[0]){
                     console.log("files are: " + file)
               }
        
       return (
              <Upload onUpload={handleUpload}/>
              <Submit onSubmit={handleSubmit}/>
        )
  }

And I have 2 components Upload and Submit, where Upload is the upload button defined like this:
It takes as input an onUpload prop through which I pass a function that sets the files.

export default function Upload ({onUpload}) {
return (
    <div >
        <input
            style={{ display: 'none' }}
            id="upload-raw-files"
            multiple
            type="file"
            onChange={onUpload}
            
        /> 
        <label htmlFor="upload-raw-files">
            <Button 
            variant="contained"
            component="span"
            size="large"
            className="Upload"
            startIcon={<UploadIcon />}
            sx={{
                
                width: '130px',
                height: '40px',
                background: '#5985F7',
                border: '3px solid #5985F7',
            }}
            >
            Upload
            </Button>
        </label>
        
    </div>
) 
}

I also have the submit component, which is simply a button through which I pass a function to submit forms

export default function Submit = ({onSubmit}) => {
return (
    <div >
        <Button 
        onClick={onSubmit}
        variant="contained"
        size="large"
        className="Submit"
        sx={{
            width: '130px',
            height: '50px',
            background: '#5985F7',
            border: '3px solid #5985F7',
            borderRadius: '25px',
        }}
        >Submit
        </Button>
    </div>
) 
}

When I upload 3 files and click submit, then inspect the console, I see that the FileList object looks like this:
FileList Object
But with the code I have, what gets printed to console is this:
What is outputted

I’m having trouble figuring out how to get access to the filename. Any help would be appreciated!

I have tried doing

for (const file in filepath[0]){
        console.log("files are: " + file[0].name)
    }

just to see if I could at least get the name of the first object, but that gives me files are: undefined.

Gatsby css slow loading times in production

I have a question for you…
I am making a documentation website with Mantine, MDX and Gatsby.
But I have a problem, when I build my app and do yarn serve, my css loads slower than the rest of my page. It has a delay.

I have installed gatsby-plugin-mantine, which didnt solve the issue.
After that I tried to use the gatsby-ssr.js file.

Which didn’t fix it either

// gatsby-ssr.js
/* eslint-disable react/jsx-filename-extension */
import React from "react";
import { renderToString } from "react-dom/server";
import { createStylesServer, ServerStyles } from "@mantine/ssr";

const stylesServer = createStylesServer();

export const replaceRenderer = ({
  bodyComponent,
  replaceBodyHTMLString,
  setHeadComponents,
}) => {
  const html = renderToString(bodyComponent);
  setHeadComponents([
    <ServerStyles html={html} server={stylesServer} key="mantine-styles" />,
  ]);
  replaceBodyHTMLString(html);
};

export const onRenderBody = ({ setHtmlAttributes }) => {
  setHtmlAttributes({ lang: "en" });
};

Any fix?
I am using “@mantine/core”: “^6.0.11”, “gatsby”: “^5.10.0”,

How to use regex to allow scientific notation for number TextField

I want to make validation for numbers with scientific notation (‘e’, ‘+’, ‘-‘, ‘.’) using regex i tried some of but that’s not working
like

Regular Numbers

/^(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i

Whole positive and negative number regex validation, supports numbers like -6e4, -16e-10, -0e0 but also regular numbers like -0, -11, and all the entire positive numbers above:

/^-?(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i
const NumberField = (props) => {
  const { errorMessege, ...restProps } = props;

  const Number = /^-?(0|[1-9]d*)(e-?(0|[1-9]d*))?$/i;
  const numberConvertor = (e) => {
    let regex = new RegExp(Number);
    let str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) return true;
    e.preventDefault();
    return false;
  };

  return (
    <TextField
      fullWidth
      onKeyPress={numberConvertor}
      helperText={errorMessege}
      error={Boolean(errorMessege)}
      {...restProps}
    />
  );
};

Clicking on iframe of current page

I’m trying to click on an element of the iframe (onpage).

I decided on the element “ablobcathungry” for now.

I can’t seem to get it to work however, no click is executed.

Are there special tricks required for this ?

The frame loads oerfectly, so thats not tge issue …

<html>
<body>
    <iframe id="my-iframe" src="https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/folder/189200124977#" style=" display:block; position: absolute; height: 100%; width: 100%" frameborder="0" ></iframe>

    <script>
        window.onload = function() {
            var myIframe = document.getElementById("myIframe");
            myIframe.onload = function() {
                var iframeDocument = myIframe.contentDocument || myIframe.contentWindow.document;
                var year2023 = iframeDocument.body.querySelector(":contains('ablobcathungry')");
                year2023.click();
            };
        };
    </script>
</body>
</html>

How to get the current window.location using a browser extension’s service worker

Due to my lack of previous experience in browser extension development, the methods I present here are my own and may not be the best approach. Please consider this in your response.

I’m trying to create an extension that turns phone numbers into clickable links. My approach to the problem involves two levels:

  1. links that I can identify with MutationObserver are managed through the content_script.js.

the content_script.js configures and manages local storage settings as follows:

chrome.storage.local.get(
    {
        sender: '',
        message: '',
        time: new Date().getHours(),
        domain: encodeURI(window.top.location.href.match(domainRegex)[1]),
    },
    function (scopedSettings) {
        settings = scopedSettings;
        if (settings.message.length == 0) {
            settings.message = `default message`;
        }

        if (settings.regexPatterns.length == 0) return;

        var mutationObserver = new MutationObserver(function (mutations) {
            mutations.forEach(function (mutation) {
                if (mutation.type == 'childList') {
                    for (var i = 0; i < mutation.addedNodes.length; i++) {
                        if (mutation.addedNodes[i].className != linkedTelClassName) {
                            walkTheDOM(mutation.addedNodes[i], handleNode);
                        }
                    }
                }
            });
        });

        ... // more code to parse `settings.domain` into `settings.message`
);

...

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        var nextNode = node.nextSibling;
        walkTheDOM(node, func);
        node = nextNode;
    }
}
  1. I created a context menu option for text selection, that is managed by background.js (service worker). Among the parameters I want to transfer is the current tab’s domain.
const contextMenuId = 'my_contextmenu_id';

...

chrome.contextMenus.onClicked.addListener(function (info, tab) {
    if (info.menuItemId !== contextMenuId) return;
    var selectedText = info.selectionText;
    chrome.storage.local.get(
        {
            sender: '',
            message: '',
            // domain: '', <== how can I get it?
            time: new Date().getHours(),
            ],
        },
        function (scopedSettings) {
            settings = scopedSettings;

            ... // more code to parse the domain into `settings.message`

        },
    );
});

In content_script.js it can be done by window.top.location.href, but in a service worker, there is no access to the window. How can he still monitor and know what is the current tab address in which he is running?

attached is the current manifest.js (v3):

{
    "author": "myself",
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
            "matches": ["https://<url_of_some_sort>"],
            "js": ["content_script.js"]
        }
    ],
    "description": "description text",
    "manifest_version": 3,
    "name": "extension",
    "permissions": ["storage", "contextMenus", "tabs"],
    "version": "0.0.1"
}

How to optimise rendering elements in a flex wrap layout

I am using React JS and I have a layout which looks like this (simplified)

...
return (
<div>
      <div className="chapter">
        {currentChapter?.content?.map((word, index) =>
              <WordItem
                key={index}
                index={index}
                word={word}
              />
        )}
      </div>
      <div className="empty"></div>
      <Slider
        className="page-slider"
        aria-label="page-slider"
        defaultValue={1}
        onChange={handleChapterChange}
        getAriaValueText={valuetext}
        step={1}
        min={1}
        max={chapterNum}
        valueLabelDisplay="auto"
        style={{ width: "96%", color: "#58BADC" }}
      />
</div>
)

In my CSS file, the div chapter has a flex-wrap layout so that each is displayed next to each other, and then goes onto a new line.
There will be hundreds of WordItem elements, so I’m trying to optimise my code so it only renders what’s in view, but I’m not sure how to do it.

I tried using react-virtualization but wasn’t sure how to implement it. I created a rowRenderer for each WordItem but I couldn’t change the number of items displayed at a time, and it got really messy really quickly.

So I was wondering what would be the best way to go about doing it, so that when I scroll down the elements can be visible straightaway instead of lagging.