POST http://localhost:8080/api/v1/dalle 500 (Internal Server Error)

I’m getting a 500 erroron the browser and a Error: Request failed with status code 400 on my node terminal. Able to console.log api key

import express from 'express';
import * as dotenv from 'dotenv';
import { Configuration, OpenAIApi } from "openai";


dotenv.config();

const router = express.Router();

const config = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(config);

console.log('API Key:', process.env.OPENAI_API_KEY);

router.route('/').get((req, res) => {
  res.status(200).json({ message: 'Hello from DALL.E ROUTES!!!' });
});

router.route('/').post(async (req, res) => {
  console.log('Received POST request:', req.body);

  try {
    const {prompt} = req.body;

    const response = await openai.createImage({
      prompt,
      n: 1,
      size: '1024x1024',
      response_format: 'b64_json',
    });

    const image = response.data.data[0].b64_json;


    res.status(200).json({ photo: image });
    
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Something went wrong' });
  }
});

export default router;

I tired passing different headers and also using a different configuration for openai.

Why does this function return void?

Here is my useSend function, I am working with Typescript + React.

const useSend = (method: string, url: string, data: any): Promise<string> => {
    return fetch(url, {
        method: method,
        headers: { 
            "Content-Type": "application/json",
            "Accept": "application/json", },
        credentials: 'include',
        body: JSON.stringify(data),
    })
    .then((response) => {  
        if (response.status === 200) {
            return "success";
        } else {
            response.json()
            .then((resp) => {
                return resp;
            });
        }
    })
    .catch(err => {
        console.log(err)
        return err;
    });
}
 
export default useSend;

When I call .then on useSend, an error is always thrown :
Cannot read properties of undefined (reading ‘then’)
TypeError: Cannot read properties of undefined (reading ‘then’)

function useSubmit (event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    const data = { email: form.get('email'), password: form.get('password') };
    
    useSend("POST", "http://localhost:2999/login", data)
        .then((temp: string) => {
            console.log(temp);
            result = temp;
            if (result == "success") {
                window.location.href = "/feed/latest";
        }
    })
}

I have made changes to the return statements and block structures but nothing helps, can someone help to explain why void is returned by this function even tho I have used then at every step to get the outer function to return after the promise is resolved?

Dynamics 365 Portal Form Show Hide Field based on Check Box Value

I’m having an issue getting Java Script to work for a Dynamics 365 portal form.

The code is supposed to show hide an address field on the form when the option for physical subscriber is selected. This is a yes no Boolean.

Here is the code:

`$(document).ready(function () {
    // Bind the onDisplaySectionChange function to the change event of the element with ID "ds_VoiceSubscriber".
    $("#ds_VoiceSubscriber").change(onDisplaySectionChange);
 
    // Calling onDisplaySectionChange immediately when the page loads.
    onDisplaySectionChange();
});
 
// Function to show or hide fields and tabs based on the selected value.
function onDisplaySectionChange() {
    var selectedValue = GetRadioSelectedValue($('#ds_VoiceSubscriber'));
 
    if (selectedValue === "1") {
        // Show the parent of the element with ID "Address1_Line1".
        $("#Address1_Line1").parent().show();
    } else {
        // Hide the parent of the element with ID "Address1_Line1".
        $("#Address1_Line1").parent().hide();
    }
}
 
// Function to get the selected value of a radio button group.
GetRadioSelectedValue = function (input) {
    if (!!$(input).find("input[type=radio]")) {
        var controlName = $(input).find("input[type=radio]").first().attr("name");
        if (!!controlName) {
            return $("input[name='" + controlName + "']:checked").val();
        }
    }
    return "";
};`

Server-side redirect in JSP with JavaScript

I want to redirect client from 1.jsp to 2.jsp using server-side redirect to avoid the redirect URL being modified and visible in client-side browser dev mode. Currently this line: window.location = "http://localhost:XXXX/XXX/2.jsp"; will expose the url in client-side browser dev mode, I want it to be hidden away from users and redirect still works.

Any possible solution to this?

1.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>This is 1.jsp</title>
    </head>
    <body>
        <script type="text/javascript">
            var width = 100;
            move();
            function move() {
                if (width >= 100) {
                    window.location = "http://localhost:XXXX/XXX/2.jsp";
                } else {
                    // rest of the code
                }
            }
        </script>
    </body>
</html>

2.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>This is 2.jsp</title>
    </head>
</html>

How to convert .jsx into .tsx

This component of the website is in .jsx while whole website is in .tsx. I want to convert this into .tsx file. Can anyone help or guide. No matter what I do, I ran into more and more errors.

extend({ RoundedPlaneGeometry: geometry.RoundedPlaneGeometry })

function Scene({ children, ...props }) {
  const ref = useRef()
  const scroll = useScroll()
  const [hovered, hover] = useState(null)
  useFrame((state, delta) => {
    ref.current.rotation.y = -scroll.offset * (Math.PI * 2) // Rotate contents
    state.events.update() // Raycasts every frame rather than on pointer-move
    easing.damp3(state.camera.position, [-state.pointer.x * 2, state.pointer.y * 2 + 4.5, 9], 0.3, delta)
    state.camera.lookAt(0, 0, 0)
  })
  return (
    <group ref={ref} {...props}>
      <Cards category="spring" from={0} len={Math.PI / 4} onPointerOver={hover} onPointerOut={hover} />
      // More Cards
    </group>
  )
}

function Cards({ category, data, from = 0, len = Math.PI * 2, radius = 5.25, onPointerOver, onPointerOut, ...props }) {
  const [hovered, hover] = useState(null)
  const amount = Math.round(len * 22)
  const textPosition = from + (amount / 2 / amount) * len
  return (
    <group {...props}>
      <Billboard position={[Math.sin(textPosition) * radius * 1.4, 0.5, Math.cos(textPosition) * radius * 1.4]}>
        <Text font={suspend(inter).default} fontSize={0.25} anchorX="center" color="black">
          {category}
        </Text>
      </Billboard>
      {Array.from({ length: amount - 3 /* minus 3 images at the end, creates a gap */ }, (_, i) => {
        const angle = from + (i / amount) * len
        return (
          <Card
            key={angle}
            onPointerOver={(e) => (e.stopPropagation(), hover(i), onPointerOver(i))}
            onPointerOut={() => (hover(null), onPointerOut(null))}
            position={[Math.sin(angle) * radius, 0, Math.cos(angle) * radius]}
            rotation={[0, Math.PI / 2 + angle, 0]}
            active={hovered !== null}
            hovered={hovered === i}
            url={`/img${Math.floor(i % 10) + 1}.jpg`}
          />
        )
      })}
    </group>
  )
}

function Card({ url, active, hovered, ...props }) {
  const ref = useRef()
  useFrame((state, delta) => {
    const f = hovered ? 1.4 : active ? 1.25 : 1
    easing.damp3(ref.current.position, [0, hovered ? 0.25 : 0, 0], 0.1, delta)
    easing.damp3(ref.current.scale, [1.618 * f, 1 * f, 1], 0.15, delta)
  })
  return (
    <group {...props}>
      <Image ref={ref} url={url} scale={[1.618, 1, 1]} side={THREE.DoubleSide} />
    </group>
  )
}

function ActiveCard({ hovered, ...props }) {
  const ref = useRef()
  const name = useMemo(() => generate({ exactly: 2 }).join(' '), [hovered])
  useLayoutEffect(() => void (ref.current.material.zoom = 0.8), [hovered])
  useFrame((state, delta) => {
    easing.damp(ref.current.material, 'zoom', 1, 0.5, delta)
    easing.damp(ref.current.material, 'opacity', hovered !== null, 0.3, delta)
  })
  return (
    <Billboard {...props}>
      <Text font={suspend(inter).default} fontSize={0.5} position={[2.15, 3.85, 0]} anchorX="left" color="black">
        {hovered !== null && `${name}n${hovered}`}
      </Text>
      <Image ref={ref} transparent position={[0, 1.5, 0]} url={`/img${Math.floor(hovered % 10) + 1}.jpg`}>
        <roundedPlaneGeometry parameters={{ width: 3.5, height: 1.618 * 3.5 }} args={[3.5, 1.618 * 3.5, 0.2]} />
      </Image>
    </Billboard>
  )
}

I used ChatGPT but it got even worse! For example I don’t even know what this error means “Type ‘MutableRefObject<Group | undefined>’ is not assignable to type ‘Ref<Group> | undefined’.
Type ‘MutableRefObject<Group | undefined>’ is not assignable to type ‘RefObject<Group>’.
Types of property ‘current’ are incompatible.
Type ‘Group | undefined’ is not assignable to type ‘Group | null’.
Type ‘undefined’ is not assignable to type ‘Group | null’.ts(2322)”!

Vue SFC Component Composition API not working. Any solutions?

I have made a project using Vue.JS 3 and I am migrating my static HTML website to Vue. I am currently using SFC and the Composition API.

Here is my directory tree of src/

src/
--- assets/
------ fonts/
------ img/
------ base.css
------ logo.svg
------ main.css
--- components/
------ MainComponent.vue
------ NavBar.vue
--- App.vue

I tried using pascal case instead of hyphen case like what others have recommended but the components won’t render. When I open chrome dev tools, all I see is the empty app div. I have made sure that I am regestering my components locally. Here is my source code:

App.vue:

<script setup lang="ts">
import NavBar from './components/NavBar.vue'
import MainContent from './components/MainContent.vue'
</script>

<template>
  <div id="app">
    <NavBar />
    <MainContent />
  </div>
</template>

<style>
@import './assets/base.css';

body {
  color: white;
  font-family: 'Segoe Script';
  background-color: var(--background-primary);
  overflow: scroll;
  overflow-x: hidden;
  margin: 0px;
  padding: 0px;
}

body::-webkit-scrollbar {
  width: 0.25rem;
  background-color: #1e1e24;
}

body::-webkit-scrollbar-track {
  background-color: #1e1e24;
}

body::-webkit-scrollbar-thumb {
  background-color: #6649b8;
}

h1 {
  font-size: 3rem;
}

/* Large Screens */
@media only screen and (min-width: 600px) {
  body {
    zoom: 80%;
  }
}

</style>

MainContent.vue:

<script setup lang="ts">
import KUTE from "kute.js";

const anim = KUTE.fromTo(
  '#blob1',
  {
    path: '#blob1'
  },
  {
    path: '#blob2'
  },
  {
    repeat: 999,
    duration: 3000,
    yoyo: true
  }
)

anim.start()
</script>

<template>
  <main
    class="blurred"
    @mouseover="($event.currentTarget as HTMLElement).classList.add('not-blurred')"
    @mouseleave="($event.currentTarget as HTMLElement).classList.remove('not-blurred')"
  >
    <section class="blue">
      <h1>To Code or Not to Code</h1>
      <p>Front-end UI and UX developer. Python Backend Creator.</p>
      <div class="curve"></div>
    </section>

    <section class="dark2" style="z-index: -1">
      <h1>WIP</h1>
      <p>
        Error ea ut pariatur, ex dolore est incidunt distinctio obcaecati ab, inventore labore
        quisquam facere a. Nostrum quisquam temporibus optio, quibusdam amet, repellendus iste
        doloribus molestiae illum ab voluptatem magnam.
      </p>
    </section>

    <section class="bubble dark2">
      <h1>WIP</h1>
      <p>
        Non, voluptatum illum rem temporibus, repellat explicabo reiciendis est obcaecati cumque,
        debitis ducimus. Repudiandae eveniet qui laboriosam consequuntur, ipsum maiores alias
        consectetur, iure libero esse quibusdam doloribus? Facere, minus maxime.
      </p>
    </section>

    <section class="dark">
      <h1>WIP</h1>
      <p>
        Dolorum tempora et officiis quod recusandae odio quisquam possimus delectus quae nesciunt
        cupiditate iure debitis tempore saepe atque, fugit repellat quasi provident magnam
        asperiores qui aliquam hic quidem enim! Doloremque.
      </p>
    </section>

    <section class="red">
      <h1>WIP</h1>
      <p>
        Sunt assumenda similique sit soluta, ea molestias tempora doloribus ab saepe odio reiciendis
        illum laudantium consequuntur quis possimus hic necessitatibus, provident incidunt, cum
        culpa mollitia alias corporis voluptate. Ullam, saepe.
      </p>
    </section>

    <div class="spacer layer1"></div>

    <section class="dark2" style="z-index: -1">
      <h1>WIP</h1>
      <p>
        Ex quia perferendis voluptatum iure repellendus, reiciendis at maxime, fugit, optio totam
        nesciunt non maiores odio minima libero. Error modi cupiditate dolorem architecto mollitia
        perferendis quas temporibus porro expedita eligendi!
      </p>
    </section>

    <div class="spacer layer2"></div>

    <section class="pink">
      <h1 style="z-index: 1">WIP</h1>
      <p style="z-index: 1">
        Est sed ea nemo, itaque laborum nostrum velit accusamus? Aperiam, nesciunt iste! Iusto
        distinctio quaerat at repellat assumenda, ipsam sit sed expedita! Impedit quasi tempora
        rerum est? Laudantium, perferendis officia!
      </p>
    </section>
    <div class="spacer layer3"></div>

    <section class="dark2">
      <h1>Contact Me</h1>
      <iframe
        src="https://canary.discord.com/widget?id=1132442213272518666&theme=dark"
        width="350"
        height="500"
        allowtransparency="true"
        frameborder="0"
        sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"
      ></iframe>
    </section>
  </main>
</template>

<style scoped>
@import "../assets/base.css";
@import '../assets/main.css';

section {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 400px;
  padding: 100px 20vw;
}

.blue {
  background-color: var(--blue);
}

.red {
  background-color: var(--red);
}

.pink {
  background-color: var(--pink);
}

.dark {
  background-color: var(--background-primary);
}

.dark2 {
  background-color: var(--background-secondary);
}

.curve {
  position: absolute;
  height: 225px;
  width: 100%;
  bottom: 0px;
  z-index: 5;
}

.curve::before {
  content: '';
  display: block;
  position: absolute;
  border-radius: 100% 50%;
  width: 55%;
  height: 100%;
  background-color: var(--background-secondary);
  transform: translate(85%, 65%);
  z-index: 20;
}

.curve::after {
  content: '';
  display: block;
  position: absolute;
  border-radius: 100% 50%;
  width: 55%;
  height: 100%;
  background-color: var(--blue);
  transform: translate(-1%, 40%);
  z-index: 20;
}

.bubble {
  z-index: 2;
}

.bubble::after {
  content: '';
  border-top-left-radius: 50% 100%;
  border-top-right-radius: 50% 100%;
  position: absolute;
  bottom: 0px;
  height: 85%;
  width: 100%;
  background-color: var(--background-primary);
  z-index: -2;
}

.svg-wave-opacity-top {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
  line-height: 0;
}

.spacer {
  aspect-ratio: 900/450;
  width: 100%;
  background-size: no-repeat;
  background-position: center;
  background-size: cover;
}

.layer1 {
  background-image: url('../assets/img/layer1.svg');
}

.layer2 {
  background-image: url('../assets/img/layer2.svg');
}

.layer3 {
  background-image: url('../assets/img/layer3.svg');
}

.flip {
  transform: rotate(90deg) scaleX(-1);
}

.blob-motion {
  position: absolute;
  transform: translateY(-20%);
  z-index: 0;
}

.blurred {
  filter: blur(50px);
  transition: all 3s;
}

@media (prefers-reduced-motion) {
  .hidden {
    transition: none;
  }
}

.not-blurred {
  filter: blur(0);
}
</style>

NavBar.vue:

<script setup lang="ts"></script>

<template>
  <nav class="navbar">
    <ul class="navbar-nav">
      <li class="logo">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">To Code or Not to Code</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">HTML</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">CSS</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">JS</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">JSON</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">XML</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">Python</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">YouTube</span>
        </a>
      </li>
      <li class="nav-item">
        <a href="example.com" class="nav-link">
          <span class="link-text fa-primary">Discord</span>
        </a>
      </li>
    </ul>
  </nav>
</template>

<style scoped>
@import '../assets/base.css';
@import '../assets/main.css';

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(-90deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes spin-reverse {
  0% {
    transform: rotate(360deg);
  }

  25% {
    transform: rotate(-90deg);
  }

  50% {
    transform: rotate(-180deg);
  }

  75% {
    transform: rotate(90deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

@-webkit-keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(-90deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@-webkit-keyframes spin-reverse {
  0% {
    transform: rotate(360deg);
  }

  25% {
    transform: rotate(-90deg);
  }

  50% {
    transform: rotate(-180deg);
  }

  75% {
    transform: rotate(90deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

@-moz-keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(-90deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@-moz-keyframes spin-reverse {
  0% {
    transform: rotate(360deg);
  }

  25% {
    transform: rotate(-90deg);
  }

  50% {
    transform: rotate(-180deg);
  }

  75% {
    transform: rotate(90deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

@-o-keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  25% {
    transform: rotate(90deg);
  }

  50% {
    transform: rotate(180deg);
  }

  75% {
    transform: rotate(-90deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@-o-keyframes spin-reverse {
  0% {
    transform: rotate(360deg);
  }

  25% {
    transform: rotate(-90deg);
  }

  50% {
    transform: rotate(-180deg);
  }

  75% {
    transform: rotate(90deg);
  }

  100% {
    transform: rotate(0deg);
  }
}

.navbar {
  position: fixed;
  background-color: var(--background-secondary);
  transition: width 500ms ease;
  z-index: 10;
}

.navbar-nav {
  list-style-type: none;
  padding: 0px;
  margin: 0px;
  display: flex;
  flex-direction: column;
  align-content: center;
  height: 100%;
}

.nav-item {
  width: 100%;
}

.nav-item:nth-last-child(2) {
  margin-top: auto;
}

.nav-link {
  display: flex;
  align-items: center;
  height: 5rem;
  color: var(--text-primary);
  text-decoration: none;
  filter: grayscale(100%) opacity(0.7);
  transition: var(--transition-speed);
}

.link-text {
  display: none;
  margin-left: 1rem;
}

.nav-link svg {
  min-width: 2rem;
  margin: 0 1.5rem;
  filter: grayscale(100%);
}

.fa-primary {
  color: #df49a6;
  fill: #df49a6;
  transition: var(--transition-speed);
}

.logo {
  font-weight: bold;
  text-transform: uppercase;
  margin-bottom: 1rem;
  text-align: center;
  color: var(--text-primary);
  background-color: var(--background-primary);
  letter-spacing: 0.3ch;
  width: 100%;
}

@media only screen and (max-width: 600px) {
  .navbar {
    bottom: 0px;
    width: 100vw;
    height: 5rem;
  }

  .logo {
    display: none;
  }

  .navbar-nav {
    flex-direction: row;
  }

  .nav-link {
    justify-content: center;
  }

  html body .hidden {
    transition: none;
  }

  main {
    margin: 0px;
    padding: 0px;
  }
}

@media only screen and (min-width: 600px) {
  body {
    zoom: 80%;
  }

  .navbar {
    top: 0px;
    width: 5rem;
    height: 100%;
  }

  .navbar:hover {
    width: 16rem;
  }

  .nav-link:hover {
    filter: grayscale(0%) opacity(1);
    background-color: var(--background-primary);
    color: var(--text-primary);
  }

  .logo svg {
    animation: spin-reverse 1s ease-in-out;
    -webkit-animation: spin-reverse 1s ease-in-out;
    -moz-animation: spin-reverse 1s ease-in-out;
    -o-animation: spin-reverse 1s ease-in-out;
  }

  .navbar:hover .logo svg {
    animation: spin 1s ease-in-out;
    -webkit-animation: spin 1s ease-in-out;
    -moz-animation: spin 1s ease-in-out;
    -o-animation: spin 1s ease-in-out;
  }

  .navbar:hover .link-text {
    display: inline;
  }
}
</style>

Expected Result (Old static website):
Working static HTML website

Actual Result (Vue Project):
Actual non-working Vue project

Dev tools of vue project:
Dev tools screenshot of non-working vue project

And console of vue project:
Console of non-working vue project

NOTE: There are SVGs in NavBar.vue and MainContent.vue but Stack Overflow limits my body length so I removed them

node js sharp weird image after resizing

after i resize image, image’s quality is low and weird mono color

sharp(req.files.file[0].path).resize({height:250})
                                  .withMetadata()
                                  .toFile(`resize/${file_server}`, (err,info) =>{
                                    if(err) throw err;
                                    console.log(`info : ${info}`);
                                  })
                                  .toBuffer();
                                } else {req.files.file[0].filename = file_server}
                                console.log(req.files.file[0].mimetype.indexOf('image'))

before resizing file

enter image description here

this is a image after resizing

enter image description here

i dont know why my image return like this.

also .png file’s resizing is just black square return

Env for Email.js

i´m using a .env file to hide my email.js, but it doesn´t work.
Putting de ids directly using ” work, but when i use .env not

import emailjs from '@emailjs/browser';
import dotenv from 'dotenv';

dotenv.config();


const sendEmail = (templateParams) => {
  emailjs.send(process.env.service_id, process.env.template_id, templateParams, process.env.user_id)
    .then((response) => {
      console.log('SUCCESS!', response.status, response.text);
    }, (error) => {
      console.log('FAILED...', error);
    });
}

export default sendEmail;

the env file is in the same folder that .gitignore file

I want to hide my keys. is there any solution.

Is there a way to go back on original state after appending child inside it with Javascript?

Is there a way to go back on original state after appending child inside it with Javascript?

This is how I append child to my div if the condition is met:
document.getElementById("myList1").appendChild("node");
And if the condition does not meet I want document.getElementById(“myList1”) go back to its normal state, without the appendChild, is there a way like this document.getElementById("myList1").reset();

I tried to parent.removeChild(child); but it removes all child of the parent, I only need to remove what was added by appendChild.

Use `eslint` without providing files on the command line?

"lint": "eslint -c .eslintrc.json --fix src/**/*.ts test/**/*.ts *.ts",
"lint:prod": "eslint -c .eslintrc.prod.json --fix src/**/*.ts test/**/*.ts *.ts",

Note the duplicative paths in these NPM scripts. And there is one more that look pretty much the same in the lint-staged config.

It seems I cannot omit the paths, and have eslint use its config file to find the files to lint:

  "overrides": [
    {
      "parser": "@typescript-eslint/parser",
      "plugins": [
        "@typescript-eslint"
      ],
      "files": [
        "src/**/*.ts",
        "test/**/*.ts",
        "*.ts"
      ]
    }
  ]

At least, with that config in place, and running npx eslint -c .eslintrc.json, no files are checked. Adding the paths to the command line does check the files.

I guess overrides[].files only tells the related parser which files to look at, but not eslint itself.

Is it not supported to just use the config file to figure out which files to check?

React Frontend not sending messages to Node.js Backend [duplicate]

I’m making an email contact form for a website and the handleSubmit function is timing out before it can connect to the node.js backend, even though the server is running. I need help getting the frontend to send data to the backend. Even though I know for sure the server runs, as when I mistakenly ran both the server and website on port 3000 the code sent undefined emails to the server (at the cost of the website ceasing to work when reloaded), the code now keeps sending 404 errors in the website console. Thank you very much!
(I’ve tried Fetch and Axios both, and neither work. The fetch code is more reliable though).

Here is the function:

function handleSubmit(event) {
  event.preventDefault();
  const form = event.target;
  const formInfo = new FormData(form);
  const jsonBody = JSON.stringify(Object.fromEntries(formInfo));
  console.log(jsonBody);
  async function fetchData() {
    await fetch("http://localhost:3002/send", {
      method: "POST",
      body: jsonBody,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      }

    })
      .then((response) => response.json())
      .then((response) => {
        if (response.status === "fail") {
          alert("Message failed to send.");
        }
      });
  }
  fetchData();
}

Even async/await isn’t helping. This was the original version:

function handleSubmit(event) {
  event.preventDefault();
  const form = event.target;
  const formInfo = new FormData(form);
  const jsonBody = JSON.stringify(Object.fromEntries(formInfo));
  console.log(jsonBody);
  fetch("http://localhost:3002/send", {
    method: "POST",
    body: jsonBody,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.status === "success") {
        alert("Message Sent.");
        this.resetForm();
      } else if (response.status === "fail") {
        alert("Message failed to send.");
      }
    });
}

This backend code was copied from a tutorial with changes:

var express = require("express");
var router = express.Router();
var nodemailer = require("nodemailer");
var cors = require("cors");
const creds = require("./config");

// email details here

router.post("/send", (req, res, next) => {
  var content = req.body;
  var mail = {
    from: " ",
    to: "[email protected]",
    subject: "New Message from Contact Form",
    text: content,
  };
  transport.sendMail(mail, (err, data) => {
    if (err) {
      res.json({
        status: "fail",
      });
    } else {
      res.json({
        status: "success",
      });
    }
  });
});
const app = express();
app.use(cors());
app.use(express.json());
app.get("/", function (req, res, next) {});
app.use("/", router);
app.listen(3002);

COMO CONECTAR O NODE COM O MONGODB? [closed]

Olá!

Estudando a conexão do MongoDB no Node.js, estou tendo um problema que não sei o que pode ser.

console.log('1');
const client = require('mongodb').MongoClient;
console.log('2');
let mongoServer = 'mongodb://localhost:27017';
console.log('3');
client.connect(mongoServer, function(err, client){
    console.log('4');
    if(err) return callback(err);
    console.log('5');
    let db = client.db('livro');
    console.log('6');
    let carros = db.collection('carros');
    console.log('7');
    carros.find({}).toArray(function(error, results){
        for(let carro of results){
            console.log(carro);
        }
    })
})

Ao executar, o programa trava na linha:
client.connect(mongoServer, function(err, client){

Não gera nenhum erro, mas pelo console trava aí.

Alguém saberia o que pode ser?