Is it good practice to use a POST request instead of PATCH to update data in a CRUD application?

I’m making a CRUD application and I’m making an update comment function. Normally, there is a patch request that is used for updating or modifying objects. However, while working on forms, I saw that the html forms only respond to GET and POST requests. This got me thinking for the UPDATE application of the CRUD, and I thought I could simply use a POST request to create the application.

html:

<form action="http://localhost:3000/update" id='POST' method="post">
    <label for="username">Username: </label>`  
    <input type="text" name='username' id='username'>
    <label for="comment">Comment:</label>
    <input type="text" name="comment" id="comment">
    <button>UPDATE</button>
</form>

Javascript:

app.post('/update', (req, res) => {

    console.log(req.body);
    const { username, comment } = req.body;
    const ind = comments.findIndex((element) => element.username === username)
    comments[ind].comment = comment;
    console.log('Comment updated!');
    res.redirect('/comments');

})

The code works as expected on my end, it updates the person’s comment and then redirects to /comments, which is a page that displays all comments, but I’m not sure if it’s good practice to do it like this.

i am trying to get the information from my movies.js file to be display on the player page based on the param

here is my progress so far on the code

    const playBtn = document.querySelector('.playBtn');
    const pauseBtn = document.querySelector('.pauseBtn');
    const forwardBtn = document.querySelector('.forwardBtn');
    const prevBtn = document.querySelector('.prevBtn');
    const vid = document.getElementById("movieDisplay");
    const { name } = useParams();
    const [movie, setMovie] = useState()

    useEffect(() => {
        // Find the movie data that matches the URL parameter
        const matchedMovie = movies.find((movie) => movie.title === name);
        setMovie(matchedMovie);
        
      }, [name]); // Re-run the effect when the URL parameter changes
      console.log(movie)

this code responded with no error just an blank screen

HTML, JavaScript, CSS, fade-in troubleshooting

I am trying to add a fade in and slide up feature to some of the content in the middle of my HTML page as I scroll down. Currently I am having issues with the fade in. I am trying to apply the fade-in to a paragraph and button tag and both of them have two classes. Their own class for styling and then a .fade-in class which applies the styles for the fade in. I am implementing the fade-in through JavaScript. At the moment though, after I applied the .fade-in styles, the content isn’t showing up on the page anymore because I set the fade-in to opacity 0. While I scroll down, the content should fade in due to the fade-in.appear class which has opacity 1 but still the content is not visible.

To do some troubleshooting, I swapped opacity transitions from .fade-in {} from 0 to 1 and from .fade-in.appear {} from 1 to 0. With this change, now content never fades out. So I have come to the conclusion that the animation never gets triggered. Also please note that I have checked the browser console for JavaScript errors and ran the files through the W3C validator for HTML files and found no errors.

Here is also the code from HTML, CSS, and JS files:

HTML:

<div class="first-section">
  <p class="our-story-text fade-in">
    We customize sneakers with a focus on timeless designs, local production, and responsibly sourced products.
  </p>
  <button onclick="navigateToAbout()" class="story-button fade-in">Our Story</button>
</div>

CSS:


.our-story-text {
  font-family: 'Montserrat', sans-serif;
  display: block;
  font-size: 14px;
  text-align: center;
  padding: 50px;
  margin-top: 70px;
  background-color: rgb(242,239,227);
  width: 100%;
  max-width: 550px;
}

.story-button {
  font-family: 'Montserrat', sans-serif;
  background-color: rgb(242,239,227);
  display: block;
  color: black;
  height: 66px;
  width: 200px;
  border-width: 2px;
  border-color: black;
  font-weight: 550;
  margin-top: -28px;
}

.story-button:hover {
  cursor: pointer;
  color: rgb(242,239,227);
  background-color: black;
}

.fade-in {
  opacity: 0;
  transition: opacity 250ms ease-in;
}

.fade-in.appear {
  opacity: 1;
}

@media (max-width: 600px) {
  .our-story-text {
    background-color: rgb(242,239,227);
    margin-top: -10px;
    max-width: 85%;
  }

  .story-button {
    margin-top: 0px;
    height: 59px;
    width: 300px;
  }
}

JavaScript:

function navigateToAbout() {
  window.location.href = 'about.html';
}

const faders = document.querySelectorAll(".fade-in");

const appearOptions = {
  threshold: 1,
  rootMargin: "0px 0px -100px 0px"
};

const appearOnScroll = new IntersectionObserver(function(entries, appearOnScroll) {
  entries.forEach(entry => {
    if (!entry.isIntersecting) {
      return;
    } else {
      entry.target.classList.add("appear");
      appearOnScroll.unobserve(entry.target);
    }
  });
}, appearOptions);

faders.forEach(fader => {
  appearOnScroll.observe(fader);
});

“Region is missing” error for Amazon S3 PutObjectCommand even though region is specified

I’m working on project where I need to upload an image file (e.g., .png) to an Amazon S3 bucket. I’ve been through many examples, and as far as I can tell, I’ve been following everything the same. I finally progressed to a point where the error I am getting is “Error: Region is missing”. However, I have specified the region, and I have double-checked it is the same region specified on my bucket in the correct format (e.g., “us-west-1”). I’m just not sure any other direction to proceed in, so any direction would be helpful. Note that the file I am trying to upload is of format:

Main photo file: [
{
fieldname: ‘mainPhoto’,
originalname: ‘mainPhoto.png’,
encoding: ‘7bit’,
mimetype: ‘image/png’,
buffer: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 ac 00 00 03 28 08 06 00 00 00 7b c3 1e 08 00 00 0c 3f 69 43 43 50 49 43 43 20 50 72 6f 66 69 … 2666634 more bytes>,
size: 2666684
}
]

Here is the code (React). The image I am trying to upload is mainPhotoFile.

require('dotenv').config();
const express = require('express');
const multer = require('multer');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
// const { getSignedURL } = require('@aws-sdk/s3-rquest-presigner')
const { Pool } = require('pg');
const cors = require('cors');
const fs = require('fs');

const app = express();
app.use(cors());

const REGION = process.env.AWS_REGION;
const BUCKET = process.env.S3_BUCKET_NAME;
// Configure AWS SDK
const s3Client = new S3Client({
  region: REGION
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
});
const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'databaseName',
  password: '********',
  port: 5432,
});
app.get('/api/projects', async(req, res) => {
  const { offset = 0, limit = 10 } = req.query;
  const rows = await pool.query('SELECT * FROM portfolio LIMIT $1 OFFSET $2', [limit, offset]);
  res.json(rows);
})

const upload = multer();

app.post('/upload', upload.fields([{ name: 'mainPhoto', maxCount: 1 }, { name: 'auxPhoto1', maxCount: 1 }]), async (req, res) => {
  try {
    const files = req.files;
    const mainPhotoFile = files.mainPhoto ? files.mainPhoto : null;
    const auxPhotoFile = files.auxPhoto1 ? files.auxPhoto1 : null;

    let mainPhotoURL = null;
    let auxPhotoURL = null;

    console.log('Main photo file:', mainPhotoFile);
    console.log('Aux photo file:', auxPhotoFile);

    if (mainPhotoFile) {
      const mainPhotoParams = {
        Bucket: BUCKET,
        Key: mainPhotoFile.originalname,
        Body: mainPhotoFile,
        ContentType: mainPhotoFile.mimetype,
      };
      const mainPhotoCommand = new PutObjectCommand(mainPhotoParams);
      const mainPhotoData = await s3Client.send(mainPhotoCommand);
      mainPhotoURL = `https://${mainPhotoParams.Bucket}.s3.${REGION}.amazonaws.com/${mainPhotoParams.Key}`;
    }

    // if (auxPhotoFile) {
    //   const auxPhotoParams = {
    //     Bucket: 'your-bucket-name',
    //     Key: auxPhotoFile.originalname,
    //     Body: fs.createReadStream(auxPhotoFile.path),
    //     ContentType: auxPhotoFile.mimetype,
    //   };
    //   const auxPhotoCommand = new PutObjectCommand(auxPhotoParams);
    //   const auxPhotoData = await s3.send(auxPhotoCommand);
    //   auxPhotoURL = `https://${auxPhotoParams.Bucket}.s3.${process.env.AWS_REGION}.amazonaws.com/${auxPhotoParams.Key}`;
    // }

    const { clientName, clientTag1, clientTag2, clientTag3, clientDesc, clientNeeds, companySolution } = req.body;

    const query = `
      INSERT INTO portfolio (
        clientname,
        clienttag1,
        clienttag2,
        clienttag3,
        clientdesc,
        clientneeds,
        companysolution,
        mainphotourl,
        auxphoto1url
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
    `;

    const values = [
      clientName,
      clientTag1,
      clientTag2,
      clientTag3,
      clientDesc,
      clientNeeds,
      companySolution,
      mainPhotoURL,
      auxPhotoURL
    ];

    await pool.query(query, values);
    res.send('Data uploaded and inserted successfully.');
  } catch (err) {
    console.error(err);
    res.status(500).send('Error uploading data and files.');
  }
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Bootstrap smooth card collapse on dynamic DOM

I’m trying to create a card collapse following this page here.
https://getbootstrap.com/docs/4.0/components/collapse/#accordion-example
I’m creating the elements dynamically. Two things I noticed was:
A: Dynamically added elements do not collapse/show on their own
B: They do not do smooth collapsing/showing

So in my case to get around problem A , I added a button click event to the button which added and removed the “show” “collapse” class for the card.

export const ToggleCard = ((dom) => {
    let collapsed = dom.lastChild;
    if(collapsed.classList.contains("show")){
        collapsed.classList.add("collapsed");
        collapsed.classList.remove("show");
    }else{
        collapsed.classList.add("show");
        collapsed.classList.remove("collapsed");
    }
});

This works but it’s not smooth toggling/collapsing like the demo on the page.
When I click, it just pops in and out. Is there any way to resolve this?

Best way to learn JavaScript? [closed]

I find Youtube videos are one of the best sources for me learning so far, with HTML, CSS and PHP however most of them are either too long with lots of repetition or too short with not enough detail.

However along with those I used a few free websites to help me learn, i would like to start learning JavaScript without YouTube tutorials.

Any websites, links etc that could help kickstart learning and progress me through the ‘beginner stage’ would be greatly appreciated!

Thank you.

Also, apologies if this isnt the type of question to send here, ive used it countless times for questions others have asked before, ive just never actually typed one out.

Build ERP system [closed]

I want to create an ERP system using:

  1. Flutetr for Every Frontend.
  2. NestJs (TS) for Backend.
  3. PostgresSQL For Database.

Could you give some advice on whether these frameworks are good for ERP systems?
and some advice on which packages I can use for this project.

How can I refresh my page in Next.js so that it updates the number of items in my cart?

I am working on a payment-success page in Next.js. On the payment page, I am taking in all the user information, saving it to the database and updating the cart successfully, but I am having a difficult time refreshing the front end to reflect the change in my cart. I am having to manually refresh the page to have the cart reflect the change. I tried using useeffect with location.reload, but that causes an infite loop because it keeps getting called every time it is reloaded, and I don’t know how to stop the infinite loop, and I tried using useRouter but I get an error saying “Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted”. I am still new to Next.js and tried to find answers online, but nothing seemed to work. How can I refresh the page so that it reflects my cart is empty so I don’t have to manually refresh my page to show that?

This is the page where I would ideally like to add the code to refresh the front end. I am calling revalidatePath on the backend to get rid of the cache, which I think is working fine.

"use client";

export default function PaymentSuccess({
  searchParams: { amount },
}: {
  searchParams: { amount: string };
}) {

  return (
    <main className="m-10 mx-auto max-w-6xl rounded-md border bg-gradient-to-tr from-blue-500 to-purple-500 p-10 text-center text-slate-100">
      <div className="mb-10">
        <h1 className="mb-2 text-4xl font-extrabold">Thank you!</h1>
        <h2 className="text-2xl">You successfully sent</h2>

        <div className="p-2 text-4xl font-bold">${amount}</div>
      </div>
    </main>
  );
}

Can I load config files for my project (tsconfig, eslintrc, prettierrc, etc.) from an npm package?

I use the same config files and utility functions across all my projects. I’m working on a shared library that I will host on npm (on an internal server).

If I add config files to this shared library, can I somehow implement these config files in new projects?

In other words, I would like to download and implement config files from a shared library, hosted on npm, in the simplest way possible.

new-project/
  src/
  test/
  package.json <= download shared library package
  ...
    <other config files are provided by shared library somehow>
  ...      

Check for pending commits in React in a Suspense-compatible way?

I wrote a simple animation hook that needs to wait for React to commit renders (for concurrent mode) before painting updates. I have something like this:

function useAnimation() {
  const hasCommittedRef = useRef(false);
  hasCommittedRef.current = false;

  useLayoutEffect(() => {
    hasCommittedRef.current = true;
  });

  const handleUpdate = () => {
    if (!hasCommittedRef.current) {
      // don't paint yet
    }
    // paint
  };
}

Without Suspense, this works perfectly. With Suspense, if the component that calls this hook renders, suspends, then unsuspends: hasCommittedRef.current would always stay false.

E.g. here’s a Codesandbox demo: https://codesandbox.io/p/sandbox/youthful-fast-7vzmkz?file=%2Fsrc%2FApp.js%3A4%2C1

import React from "react";

const infiniteThenable = { then() {} };

function Inner() {
  console.log("Inner");

  const [isSuspended, setIsSuspended] = React.useState(true);

  React.useEffect(() => {
    setTimeout(() => {
      setIsSuspended(false);
    }, 500);
  }, []);

  if (isSuspended) {
    throw infiniteThenable;
  }
}

export default function App() {
  console.log("App");

  React.useLayoutEffect(() => {
    console.log("App effect");
  });

  return (
    <React.Suspense>
      <Inner />
    </React.Suspense>
  );
}

This logs:

App
Inner
App effect
Inner

Since the useLayoutEffect doesn’t run again, I can’t use this method to check if there’s a pending commit. Is there a way to check for pending commits that works with Suspense?

How to import local files using Groovy [closed]

i’m working with jmeter JSR223 postprocessors and i need help to convert a javascript code to Groovy, my Javascript code is:

// Lee el contenido de crypto-js.js desde el archivo descargado
load('C:/Users/hlopezgu/Desktop/cryptojs/node_modules/crypto-js/crypto-js.js');
load('C:/Users/hlopezgu/Desktop/cryptojs/node_modules/crypto-js/enc-utf8.js');

I need import these libraries using Groovy

Thanks in advance

Load local JS file in Puppeteer for testing

I am trying to write unit tests for JS code using Node.js, but the JS code will ultimately run in the browser and in some cases depends on browser-only objects (like document). I’m trying to get Puppeteer to work in this context, but can’t seem to get past the basics.

The code I am testing is bundled into a single JS file, so I’m using the addScriptTag of the page object in Puppeteer to add this JS file, then using page.evaluate to execute my test code.

My JS bundle (the code under test) exports a single object, and when I try to access this object from within the evaluate execution, it is undefined. In trying to track down why, I discovered that addScriptTag doesn’t seem to add anything, and the document.scripts array is empty.

Here’s an example:

const browser = await puppeteer.launch();
const page = await browser.newPage();

await page.addScriptTag({ 
  path: '/foo/bar/somescript.js', // This path is fake, but in my actual environment is correct
}).catch(error => console.log(error));

const result = await page.evaluate(() => {
  return document.scripts;
}).catch(error => console.log(error));

console.log(result.length); // This returns undefined!

await browser.close();

Does anyone know what is missing from the above to get the script to be added to the page?

Solve Turn Assign

I am doing a proyect of a game in javascript native with node.js and express and I have a question, I have done the code but sometimes work and others not becuase there seems to be an issue with the socket.id but I don’t understand how to fix it.

Client

if (!turnEmitted) {
    socket.emit('turn', { gameID: gameID });
    localStorage.setItem(`turnEmitted_${gameID}`, 'true');
}

socket.on('getCurrentPlayer', (currentPlayer) => {
    console.log(currentPlayer)
    console.log(socket.id)
    currentPlayerFront = currentPlayer.name;
    localStorage.setItem('currentPlayer', currentPlayerFront);
    if (currentPlayer.id === socket.id) {
        socket.emit('sendCurrentPlayer', {player: currentPlayerFront, gameID: gameID})
        questionsZone.style.pointerEvents = 'auto';
        diceButton.disabled = false;
    }
});

socket.on('sendCurrentPlayer', (currentPlayer) => {
    playerTurn(currentPlayer)
})

Server

socket.on('turn', async (data) => {
        const game = await Game.findOne({ gameID: data.gameID })
        if (game && game.start) {
            if (game.players.length != 0) {
                game.turn = Math.floor(Math.random() * game.players.length)
                await game.save()
                console.log('turno: ' , game.turn)
                let currentPlayer = {id: socket.id, name: game.players[game.turn].name}
                console.log('Es el turno de:', currentPlayer.name);
                io.emit('getCurrentPlayer', currentPlayer)
            }
        }
    })

socket.on('sendCurrentPlayer', (data) => {
      io.emit('sendCurrentPlayer', data.player)
})

The turn system works as expected