How i use path of file in npm packages, but i have Arraybuffer of file

I want use node-qpdf2 in my project. but the problem is that need fo file path, but i have only Arraybuffer/buffer/remoteUrl of the file. so how use this packages.

const data = await fetch(`https://api.telegram.org/file/bot7035670601:AAGm8l2ATEOFuNoftUyBY8eG5jVuCT8UCgI/${img.file_path}`)
    const buff = await data.arrayBuffer()
    const buf = Buffer.from(buff) // CONVERT TO BUFFER FROM BUFFER ARRAY
    

I have this this buffer and to use this in below code.

import { encrypt } from "node-qpdf2";

const pdf = {
  input: "./test/example.pdf",
  output: "/tmp/encrypted.pdf",
  password: "1234",
}

await encrypt(pdf);

how i can do this or any other approach to achieve this

Title: Optimizing Chrome Extension for Efficient Detection of DOM Validation Errors

I am developing a Chrome extension aimed at detecting validation errors associated with DOM elements, such as those encountered during input validation for example an email input and display a suggestion to the user in a chat widget.

Current Approach:
Currently, I am employing a method within the content script to monitor DOM changes, particularly in scenarios where the target page operates as a Single Page Application (SPA). My current solution utilizes a MutationObserver along with a debouncing technique. While this approach offers functionality, it comes with a caveat: the MutationObserver process can be resource-intensive, potentially impacting the performance of the target page.

Request for Suggestions:
I am seeking suggestions for a more optimized approach to achieve efficient validation error detection within the DOM. Any insights or alternative techniques that can enhance performance while maintaining accuracy would be greatly appreciated.

Flask + JS, Flash function doesn’t work in real time after the POST action but need a refresh to be showed

Why when i use Flask + JS – Ajax the Flask return Flash doesn’t work? I have to update the page to show the Flash message after the POST operation

I have this html

{% for p in cliente.pratiche %}
                            <tr>
                                <td id="idpratica_{{ p.idpratica }}" data-field="idpratica">{{ p.idpratica }}</td>
                                <td id="descrizione_{{ p.idpratica }}" data-field="descrizione" contenteditable="true">{{ p.descrizione }}</td>
                                <td id="idcliente_{{ p.idpratica }}" data-field="idcliente" style="display: none;">{{ p.idcliente }}</td>

                                <td id="idstato_pratica{{ p.idpratica }}" data-field="idstato_pratica" contenteditable="true">
                                    <select class="form-control" id="idstato_select_{{ p.idpratica }}">
                                        {% for stato in lista_stati %}
                                        <option value="{{ stato.idstato_pratica }}" {% if stato.idstato_pratica==p.stato_pratica_rel.idstato_pratica %} selected {% endif %}>{{ stato.descrizione }}</option>
                                        {% endfor %}
                                    </select>
                                </td>

                                <td id="idtipo_richiesta_{{ p.idpratica }}" data-field="idtipo_richiesta" contenteditable="true">
                                    <select class="form-control" id="idtipo_select_{{ p.idpratica }}">
                                        {% for tipo in lista_tipi %}
                                        <option value="{{ tipo.idtipo_richiesta }}" {% if tipo.idtipo_richiesta==p.tipo_richiesta_rel.idtipo_richiesta %} selected {% endif %}>{{ tipo.descrizione }}</option>
                                        {% endfor %}
                                    </select>
                                </td>


                                <td id="importo_{{ p.idpratica }}" data-field="importo" contenteditable="true">{{ p.importo }}</td>
                                <td>
                                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#confermaModifica{{ p.idpratica }}">Modifica</button>
                                    <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#confermaCancellazione{{ p.idpratica }}">Cancella</button>
                                    <button type="button" class="btn btn-warning" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                                        Dettagli
                                    </button>
                                    
                                </td>
                            </tr>
                            <tr>
                                <th colspan=6>
                                    <div class="collapse" id="collapseExample">
                                        <div class="card card-body">
                                            da compilare con tabella Eventi.
                                        </div>
                                    </div>
                                </th>
                            </tr>

                                        <!-- Modal Modifica -->
                                        <div class="it-example-modal">
                                            <div class="modal" tabindex="-1" role="dialog" id="confermaModifica{{ p.idpratica }}">
                                                <div class="modal-dialog" role="document">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title">Conferma operazione</h5>
                                                        </div>
                                                        <div class="modal-body">
                                                            <p>Vuoi procedere con la modifica ?</p>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button class="btn btn-outline-primary btn-sm" type="button" data-dismiss="modal">Ritorna</button>
                                                            <a class="btn btn-primary btn-sm text-white" onclick="confermaModifica({{ p.idpratica }})" role="button">Conferma</a>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

<script>
    function confermaModifica(idPratica) {
        const descrizione = document.getElementById('descrizione_' + idPratica).innerText;
        const idcliente = document.getElementById('idcliente_' + idPratica).innerText;

        const idstatoSelect = document.getElementById('idstato_select_' + idPratica);
        const idstatopratica = idstatoSelect.options[idstatoSelect.selectedIndex].value;

        const idtipoSelect = document.getElementById('idtipo_select_' + idPratica);
        const idtiporichiesta = idtipoSelect.options[idtipoSelect.selectedIndex].value;

        const importo = document.getElementById('importo_' + idPratica).innerText;

        var formData = new FormData();
        formData.append('descrizione', descrizione);
        formData.append('idcliente', idcliente);
        formData.append('idtipo_richiesta', idtiporichiesta);
        formData.append('idstato_pratica', idstatopratica);
        formData.append('importo', importo);
        formData.append('idpratica', idPratica);

        fetch('/pratica_edit', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (response.ok) {
                    $('#confermaModifica'+idPratica).modal('hide');
                    //location.reload();
                } else {
                    console.error('Errore durante l'aggiornamento del cliente:', response.statusText);
                }
            })
    }
</script>


and this the the flask backend


@pratiche_blueprint.route("/pratica_edit", methods=['POST'])
@login_required
def edit_pratica():
    descrizione = request.form['descrizione']
    idcliente = request.form['idcliente']
    idtipo_richiesta = request.form['idtipo_richiesta']
    idstato_pratica = request.form['idstato_pratica']
    importo = request.form['importo']
    idpratica = request.form['idpratica']
    pratica_obj = Pratica.query.get(idpratica)
    
    if pratica_obj:
        pratica_obj.descrizione = descrizione
        pratica_obj.idtipo_richiesta = idtipo_richiesta
        pratica_obj.idstato_pratica = idstato_pratica
        pratica_obj.importo = importo
        pratica_obj.idcliente = idcliente

        try:
            db.session.commit()
            log_this(current_user.iduser, idpratica, idstato_pratica, 'Aggiornamento')
            flash('Aggiornamento avvenuto con successo.', 'success-custom')
            return make_response('success', 200)
        except Exception as e:
            flash('Query Error #f1', 'danger-custom')
            db.session.rollback()
            return make_response("Errore edit pratica %s" % str(e), 500)
    else:
        flash('Pratica non trovata', 'danger-custom')
        return make_response('Pratica non trovata', 404)
    
    return redirect(request.referrer)

The flash message in True case of the Try isn’t showed in real time but after a refresh of the page. This happens any time i use a POST request throught JS, that some times i need for more complex works and flask-form isn’t enough. When i use flask-form the Flash message works properly

Carousel script does not restart

The carousel does not restart after showing 3 pictures .

I want the carousel go back to picture 1 after the last picture : in automatic mode and also in manual mode

The html is showing 3 pictures. After the last picture, it shows blanks, the whole picture is disappeared

<script>
  // gallery automatic

  var slideIndex = 0
  var timer = null
  carousel()

  function carousel() {
    var i
    var x = document.getElementsByClassName('mySlides')
    for (i = 0; i < x.length; i++) {
      x[i].style.display = 'none'
    }
    slideIndex++
    if (slideIndex > x.length) {
      slideIndex = 1
    }
    x[slideIndex - 1].style.display = 'block'
    timer = setTimeout(carousel, 6000)
  }

  var slideIndex = 1
  showDivs(slideIndex)

  function plusDivs(n) {
    showDivs((slideIndex += n))
  }

  // gallery manual
  function showDivs(n) {
    clearTimeout(timer)
    var i
    var x = document.getElementsByClassName('mySlides')
    if (n > x.length) {
      slideIndex = 1
    }
    if (n < 1) {
      slideIndex = x.length
    }
    for (i = 0; i < x.length; i++) {
      x[i].style.display = 'none'
    }
    x[slideIndex - 1].style.display = 'block'
    timer = setTimeout(carousel, 6000)
  }
</script>

HTML Javascript donut chart doesnt appear using Chart.js

I have this HTML code to show a donut chart with the database records retrieved from the database via a PHP script. The data is being retrieved successfully and can be seen on the browser console.
But the chart is not displayed. How do I fix this?

console.log('Script loaded'); // Check if script is loaded

// Fetch total number of students from PHP file using fetch API
fetch('/javatopia/api/lvTotalStudents.php')
  .then(response => response.json())
  .then(data => {
    console.log('Total Students Data:', data); // Log total students data
    document.getElementById('totalStudents').innerHTML = 'There are currently <strong>' + data.totalStudents + '</strong> students enrolled.';
  })
  .catch(error => {
    console.error('Error fetching total number of students:', error);
  });

// Fetch module names and IDs from PHP file using fetch API and populate dropdown menu
fetch('/javatopia/api/lvParticipationPerModule.php')
  .then(response => response.json())
  .then(data => {
    console.log('Fetched Modules:', data); // Log fetched module data
    const moduleSelect = document.getElementById('moduleSelect');
    data.forEach(module => {
      const option = document.createElement('option');
      option.value = module.moduleId;
      option.text = module.moduleName;
      moduleSelect.appendChild(option);
    });
  })
  .catch(error => {
    console.error('Error fetching module data:', error);
  });

// Fetch data for line chart and initialize the chart
fetch('/javatopia/api/lvPerformance.php')
  .then(response => response.json())
  .then(data => {
    console.log('Line Chart Data:', data); // Log line chart data
    // Prepare data for Chart.js line chart
    const topics = Object.keys(data);
    const averageMarks = Object.values(data);
    const ctxLine = document.getElementById('averageMarks').getContext('2d');

    new Chart(ctxLine, {
      type: 'line',
      data: {
        labels: topics,
        datasets: [{
          label: 'Average Marks per Topic',
          data: averageMarks,
          fill: false,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
            max: 5, // Set the maximum value for the y-axis
          }
        }
      }
    });
  })
  .catch(error => {
    console.error('Error fetching line chart data:', error);
  });

// Set default module ID and event listener for "Go" button click
document.addEventListener('DOMContentLoaded', function() {
  console.log('DOM Loaded'); // Check if DOM is loaded
  const defaultModuleId = 3; // Set your default module ID here
  document.getElementById('moduleSelect').value = defaultModuleId;
  fetchModuleCompletionData(defaultModuleId);
});

document.getElementById('goButton').addEventListener('click', function() {
  console.log('Go Button Clicked'); // Check if Go button is clicked
  const selectedModuleId = document.getElementById('moduleSelect').value;
  fetchModuleCompletionData(selectedModuleId);
});

// Function to fetch and update module completion data for the donut chart
function fetchModuleCompletionData(moduleId) {
  moduleId = parseInt(moduleId); // Convert moduleId to a number
  console.log('Fetching Module Completion Data for Module ID:', moduleId);

  fetch(`/javatopia/api/lvParticipationPerModule.php?moduleId=${moduleId}`)
    .then(response => response.json())
    .then(data => {
      console.log('Module Completion Data:', data); // Log module completion data
      const ctxDonut = document.getElementById('moduleCompletionChart').getContext('2d');
      let moduleCompletionChart = window.moduleCompletionChart;
      if (moduleCompletionChart && moduleCompletionChart.data) {
        moduleCompletionChart.data.labels = ['Completed', 'Not Completed'];
        moduleCompletionChart.data.datasets[0].data = [data.completed, data.not_completed];
        moduleCompletionChart.update();
      } else {
        window.moduleCompletionChart = new Chart(ctxDonut, {
          type: 'doughnut',
          data: {
            labels: ['Completed', 'Not Completed'],
            datasets: [{
              label: 'Module Completion',
              data: [data.completed, data.not_completed],
              backgroundColor: ['#36A2EB', '#FF6384'],
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false
          }
        });
      }

      // Ensure the canvas is visible and not hidden
      const canvas = document.getElementById('moduleCompletionChart');
      if (canvas) {
        canvas.style.display = 'block';
      }
    })
    .catch(error => {
      console.error('Error fetching module completion data:', error);
    });
}
<link href="/javatopia/lib/bootstrap/assets/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>

<div id="totalStudents" align="center" style="position: relative; margin-top: 3vw; margin-bottom: 0.5vw;"></div>
<div id="averagePointsPerTopic" class="chart-container" align="center" style="position: relative; height:20vh; width:40vw; margin-top: 2.5vw; margin-bottom: 15vw; margin-left: 30vw;">
  <h2>Average performance per topic</h2>
  <canvas id="averageMarks"></canvas>
</div>
<div id="donutChartContainer" align="center" style="position: relative; margin-left: 35vw; height: 20vw; width: 30vw; margin-top: 2.5vw; margin-bottom: 15vw;">
  <h2>Module Completion</h2>
  <select id="moduleSelect">
    <!-- Options will be populated dynamically -->
  </select>
  <button id="goButton">Go</button>
  <canvas id="moduleCompletionChart" style="display: block;"></canvas>
</div>

Below is the console log

lvDashboard3.2.html:24 Script loaded
lvDashboard3.2.html:92 DOM Loaded
lvDashboard3.2.html:107 Fetching Module Completion Data for Module ID: 3
lvDashboard3.2.html:30 Total Students Data: {totalStudents: 4}
lvDashboard3.2.html:58 Line Chart Data: {Intro: '2.50', Syntax: '3.75', Output: '2.50', Comments: '2.50'}
lvDashboard3.2.html:41 Fetched Modules: (4) [{…}, {…}, {…}, {…}]
lvDashboard3.2.html:112 Module Completion Data: (4) [{…}, {…}, {…}, {…}]

The donut chart to be shown on the page

Error: Collecting page data for undefined is still timing out after 2 attempts. https://nextjs.org/docs/messages/page-data-collection-timeout

I am deploying my git repo to vercel and seeing this error

My Repo :- https://github.com/SH20RAJ/shadev2/tree/dev

Whats the problem how to fix it and deploy my website online.

PS: My Website is properly working on localhost and GitHub Codespaces

Error: Collecting page data for undefined is still timing out after 2 attempts. See more info here https://nextjs.org/docs/messages/page-data-collection-timeout — 21:32:45.793 | at onRestart (/vercel/path0/node_modules/next/dist/build/index.js:303:27) 21:32:45.794 | at Worker.isPageStatic (/vercel/path0/node_modules/next/dist/lib/worker.js:95:40) 21:32:45.794 | at process.processTicksAndRejections (node:internal/process/task_queues:95:5) 21:32:45.794 | at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:151:20) 21:32:45.794 | at async /vercel/path0/node_modules/next/dist/build/index.js:1047:56 21:32:45.794 | at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:151:20) 21:32:45.795 | at async Promise.all (index 3) 21:32:45.795 | at async /vercel/path0/node_modules/next/dist/build/index.js:979:17 21:32:45.795 | at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:151:20)

Provide environment information
I’m deploying on vercel

The Build should be completed and my website gets deployed

There is an issue with Bangla character counting on every website

Recently I’ve noticed a bizarre problem. I have a script that counts the number of SMS and characters typen for both Bangla and English characters. I wrote the script over 2 years ago with the help of the community and have been using this since then without any issues. Last few months all SMS was sent in English. Today when I was typing the message I noticed that the very first character I type is being counted as 91 characters which wasn’t correct. for the next few (the rest of the characters) characters it counts as usual. Below I’m sharing the script –

(function ($) {
    $.fn.smsArea = function (options) {
        var e = this,
            cutStrLength = 0,

            s = $.extend({
                cut: true,
                maxSmsNum: 5,
                interval: 400,

                counters: {
                    message: $('#smsCount'),
                    character: $('#smsLength')
                },

                calculateSmsMaxLength: function (isUnicode, writtenSmsNb) {
                    if (isUnicode) {
                        if (writtenSmsNb == 0) {
                            return 70;
                        } else {
                            return (70 * (writtenSmsNb + 1)) - ((writtenSmsNb + 1) * 3);
                        }
                    } else {
                        if (writtenSmsNb == 0) {
                            return 160;
                        } else {
                            return (160 * (writtenSmsNb + 1)) - ((writtenSmsNb + 1) * 7);
                        }
                    }
                }
            }, options);

        e.keyup(function () {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(function () {
                var smsType,
                    smsLength = 0,
                    smsCount = -1,
                    charsLeft = 0,
                    text = e.val(),
                    isUnicode = false;

                for (var charPos = 0; charPos < text.length; charPos++) {
                    switch (text[charPos]) {
                        case "n": case "[": case "]": case "\": case "^": case "{": case "}": case "|": case "€":
                            smsLength += 2;
                            break;

                        default:
                            smsLength += 1;
                    }

                    if (text.charCodeAt(charPos) > 127 && text[charPos] != "€")
                        isUnicode = true;
                }

                for (var sCount = 0; sCount < s.maxSmsNum; sCount++) {
                    smsType = s.calculateSmsMaxLength(isUnicode, sCount);
                    cutStrLength = smsType;
                    if (smsLength <= smsType) {
                        smsCount = sCount + 1;
                        charsLeft = smsType - smsLength;
                        break
                    }
                }

                if (s.cut) e.val(text.substring(0, cutStrLength));
                smsCount == -1 && (smsCount = s.maxSmsNum, charsLeft = 0);

                s.counters.message.html(smsCount);
                s.counters.character.html(charsLeft);
            }, s.interval)
        }).keyup();
    }
}(jQuery));

I’ve trie­d to debug the problem, but with my curre­nt knowledge, I couldn’t identify the­ issue. What’s even more­ perplexing is that the same­ problem persists in some online­ tools. Please re­fer to the attached scre­enshot for clarification.

enter image description here

I am reaching out to seek your assistance in resolving this issue. I may be overlooking something, so any help you can provide would be greatly appreciated.

Thank you so much for your attention and participation.

Play video in html5 video while fetching data

i want to play a video on my website inside a html video-tag. The video file is fetched from the backend and converted into a blob, which is placed in the src-attribute of the video-tag.

My problem is, that some videos are big 160kb which takes around 10 seconds until the fetch() is complete. Is it possible to play the video during the fetch() and not wait until the end with a buffer or something?

     fetchResult = await fetch(`/Content/GetFileFromPath`, {
      headers: { ...headers, 'Content-Type': 'application/json' },
      method: 'POST',
      body: JSON.stringify(props.content.Path),
    })

After the fetch() the response is converted in blob()

    if(fetchResult.status == 200) {
     const blob = await fetchResult.blob();
     const oUrl = URL.createObjectURL(blob);
     setObjectUrl(oUrl);

Google Analytics 4 custom events are not being sent

I’m implementing GA4 on a site. The code looks like this:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-K..."></script>
    <script>
      console.log(window.dataLayer)
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-K...');
      gtag('event', 'testing', { 'start': 'true' })
    </script>

What I see in the network tab is one ‘collect’ request at load, and another a few seconds later.

enter image description here

Adding further event calls never triggers an actual network request.

I’m using Safari for this testing with no privacy features, so it’s not that network requests are being blocked.

Is there another explanation for why the event call is not doing anything?

Getting CORS policy error in Next.js while making Axios request [duplicate]

I’m encountering a CORS policy error when attempting to make a POST request using Axios in a Next.js application. The error message states: ‘Access to XMLHttpRequest at [API_URL] from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.’ I’ve tried adding ‘Access-Control-Allow-Credentials’ and ‘Access-Control-Allow-Origin’ headers to the request configuration, but the error persists. How can I resolve this CORS issue in my Next.js application when using Axios for API requests?

my code

const formData = new FormData();
formData.append("email", "email");
formData.append("password", "token");

const config = {
    method: 'post',
    url: 'https://notify.eskiz.uz/api/auth/login',
    headers: { 
        'Content-Type': 'multipart/form-data', 
        'Accept': '*/*',
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': '*'
    },
    data : formData
};

axios(config)
    .then(function (response) {
        console.log(response.data);
    })
    .catch(function (error) {
        console.log(error);
    });

Results in english when searching address in hebrew

I’m trying to search an address in Israel by passing query string in hebrew. In some cases, I’m getting results where the city is returned in english, when I expecting the entire result to be in hebrew:
https://api.mapbox.com/geocoding/v5/mapbox.places/%D7%90%D7%97%D7%95%D7%96%D7%94%20%D7%A8%D7%A2%D7%A0%D7%A0%D7%94.json?country=il&proximity=ip&language=he&access_token=pk.eyJ1Ijoic2VyZ2V5YnVyZDIwMCIsImEiOiJjbGkwMDI2b3UxajM0M3VxYWgwd29oYzZhIn0.3Mc-RtsOie0z1Ga6dcdzvg

Notice that both place_name_he and place_name contain english text.
It seems some cities in Israel have no hebrew translations.

Do you know about this issue?

Thanks,
Yossi

I tried to search address by entering text in hebrew. I expected to get results in hebrew. But results contain english.

Access Denied – NextJs API and API provide 403 Forbidden Error due to Sucuri Website Firewall

I created a Nextjs backend and called the api in the page routing pages/api/SubmitForm. This API runs well locally, but fails to execute at the domain and returns a 403 Forbidden banned message. How I resolve it and response come is

Access Restrictions – Sucuri Website Security
Please whitelist your IP if you are the site owner or manager, or create a support ticket with the specifics of the block (seen in the box below) if you believe this is an error so we can help you troubleshoot the problem.

Block reason: An attempted XSS (Cross site scripting) was detected and blocked.

Below I am sharing Api and Api call for Nextjs Please check and give suggest as soon as

Api Call :-

export async function mailManagement(formData)
{
  try {
    const response = await axios.post('/api/submitForm',formData);
    console.log(response.data);
  } catch (error) {
    console.error('Error submitting form:', error);
  }
} 

Api In Nextjs :-

import nodemailer from 'nodemailer';

export default async function handler(req, res) {

  if (req.method === 'POST') {
    try {
      const formData = await req.body; 
      const transporter = nodemailer.createTransport({
        host: "smtpXXX.com",
        port: 465,
        secure: true,
        auth: {
          user: "XXXXXXX",
          pass: "XXXXXXX",
        },tls: {
          ciphers:'SSLv3',
          rejectUnauthorized: false
        },
      });

      for (const data of formData) {
        const mailOption = {
          from: "[email protected]",
          to: data.send_to,
          cc: data.cc_emails,
          subject: data.subject,
          html: data. View,
        };     
        const response = await transporter.sendMail(mailOption);
      }

      res.status(200).json({ message: "Contact Form Email Sent Successfully" });
    } catch (error) {
      console.error("Error sending email:", error);
      res.status(500).json({ message: "Failed to Send Email" });
    }
  } else {
    res.status(405).json({ error: 'Method Not Allowed' });
  }
}

And Response in Api :-

Sucuri Error in Api Response

I try using cors library for my domain but not work and whitelisting my IP address, but they aren’t practical for me. I am unable to whitelist every IP address since it gives an error when a different user submits a form from anywhere in the world.

I am expecting that my problem solve as soon as possible .

Internal Server Error: Failed to Resolve Entry for Package ‘@reduxjs/toolkit

I encountered an internal server error while working on my project. The error message states: “Failed to resolve entry for package ‘@reduxjs/toolkit’. The package may have incorrect main/module/exports specified in its package.json.” I’ve checked and ensured that the Redux Toolkit package is installed in my project. Despite this, the error persists. I’m importing the createSlice function from Redux Toolkit using the following statement:

import { createSlice } from “@reduxjs/toolkit”;
Could someone please help me identify the root cause of this error and provide guidance on how to resolve it?

I’ve encountered an internal server error while working on my project. The error message suggests that there’s a problem resolving the entry for the package @reduxjs/toolkit. To address this issue, I’ve taken the following steps:

Verified that Redux Toolkit is installed in my project using the command npm install @reduxjs/toolkit.

Checked the import statement to ensure correctness:

import { createSlice } from “@reduxjs/toolkit”;

Encryption & Decryption with RSA PKCS1 PADDING in Express js

I am using express js. Encryption and decryption completely works in node 14 BUT in node 20 it says RSA_PKCS1_PADDING is no longer supported for private decryption, this can be reverted with –security-revert=CVE-2023-46809

I don’t wont to use security-revert=CVE-2023-46809

Besides I have to use RSA PKCS1 PADDING algorithm with PKCS1 padding algorithm

Thanks in advance

  const crypto = require('crypto');

  encrypt(data) {
     const signerObject = crypto.publicEncrypt(
        { key: this.pubKey, padding: crypto.constants.RSA_PKCS1_PADDING },
        Buffer.from(JSON.stringify(data))
     );
     return signerObject.toString('base64');
   } 


   decrypt(data) {
      const decrypted = crypto
          .privateDecrypt({ key: this.privKey, padding: crypto.constants.RSA_PKCS1_PADDING },  Buffer.from(data, 'base64'))
        .toString();
      return JSON.parse(decrypted);
    }

Please suggest a solution how to resolve this in node 20

Filtering posts by category in React shows “Posts not found” despite posts existing

I am developing a feature in a React application that allows users to filter posts by categories using Firestore as the database. When a user selects a category from the menu bar, the application should only display posts belonging to that selected category. However, I encounter a “Posts not found” error even though I have confirmed the posts with the corresponding categories exist in Firestore.

Here is the menu bar component where categories are selected:

import React, { useState } from 'react';
import { Box, useDisclosure } from '@chakra-ui/react';
import useSearchUsersPosts from '../../hooks/useSearchUserPosts';
import FeedPost from '../FeedPosts/FeedPost';
import PostPageContent from '../PostPage/PostPageContent';

const categories = [
  { name: "Dorm & Living", value: "dormLiving" },
  { name: "Electronics", value: "electronics" },
  { name: "Clothing, Shoes, & Accessories", value: "clothingShoesAccessories" },
  { name: "Bags & Luggage", value: "bagsLuggage" },
  { name: "Books & Study Materials", value: "booksStudyMaterials" },
  { name: "Outdoor & Sports", value: "outdoorSports" },
];

const Menubar = () => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { posts, isLoading, getPostDetails } = useSearchUsersPosts();
  const [selectedCategory, setSelectedCategory] = useState("");

  const handleCategoryClick = (categoryValue) => {
    setSelectedCategory(categoryValue);
    getPostDetails(categoryValue, );
  };

  return (
    <>
      <Box display="flex" alignItems="start">
        {categories.map((category) => (
          <Box 
            key={category.value} 
            p="2" 
            _hover={{ bg: 'gray.100', cursor: 'pointer' }}
            onClick={() => handleCategoryClick(category.value)}
          >
            {category.name}
          </Box>
        ))}
      </Box>
      {posts &&
        posts.map((post, index) => (
          index % 25 === 0 ? (
            <FeedPost
              postData={post}
                key={post.id}
                id={post.id}
            />
          ) : null
        ))
      }
    </>
  );
};

export default Menubar;

And here is the custom hook (useSearchUsersPosts) where I fetch posts based on the selected category:

import React, { useState } from 'react';
import { Box, useDisclosure } from '@chakra-ui/react';
import useSearchUsersPosts from '../../hooks/useSearchUserPosts';
import FeedPost from '../FeedPosts/FeedPost';
import PostPageContent from '../PostPage/PostPageContent';

const categories = [
  { name: "Dorm & Living", value: "dormLiving" },
  { name: "Electronics", value: "electronics" },
  { name: "Clothing, Shoes, & Accessories", value: "clothingShoesAccessories" },
  { name: "Bags & Luggage", value: "bagsLuggage" },
  { name: "Books & Study Materials", value: "booksStudyMaterials" },
  { name: "Outdoor & Sports", value: "outdoorSports" },
];

const Menubar = () => {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { posts, isLoading, getPostDetails } = useSearchUsersPosts();
  const [selectedCategory, setSelectedCategory] = useState("");

  const handleCategoryClick = (categoryValue) => {
    setSelectedCategory(categoryValue);
    getPostDetails(categoryValue, );
  };

  return (
    <>
      <Box display="flex" alignItems="start">
        {categories.map((category) => (
          <Box 
            key={category.value} 
            p="2" 
            _hover={{ bg: 'gray.100', cursor: 'pointer' }}
            onClick={() => handleCategoryClick(category.value)}
          >
            {category.name}
          </Box>
        ))}
      </Box>
      {posts &&
        posts.map((post, index) => (
          index % 25 === 0 ? (
            <FeedPost
              postData={post}
                key={post.id}
                id={post.id}
            />
          ) : null
        ))
      }
    </>
  );
};

export default Menubar;

I considered the possibility that the FeedPost component might be missing category or condition fields, but my intent is not to display all post details in the feed – only when viewing the post’s content directly.
feddpost

<Text>{"$" + postData.price}</Text>
{postData.title}

post content:

<Heading as="h1" size="md">
            {posts?.title}
          </Heading>
          {/* description */}
          <Text as="p" my={2}>
            {posts?.description}
          </Text>
          {/* price */}
          <Text as="h4" fontWeight="bold">
            {"$ " + posts.price}
          </Text>
        </Box>
        <Flex my={4}>
          <Text fontSize={{ base: 12, md: 12, lg: 16 }}>Size L </Text>
          <Text px={{ base: 1, md: 1, lg: 1.5 }}> &#x2022;</Text>
          {/* Condition */}
          <Text fontSize={{ base: 12, md: 14, lg: 16 }}>
            {posts?.condition}{" "}
          </Text>{" "}
          <Text px={{ base: 1, md: 1, lg: 1.5 }}> &#x2022;</Text>
          {/* category */}
          <Text fontSize={{ base: 12, md: 14, lg: 16 }}>
            {" "}
            {posts?.category}
          </Text>
          <Text px={{ base: 1, md: 1, lg: 1.5 }}> &#x2022;</Text>
          {/* title */}
          <Text fontSize={{ base: 12, md: 14, lg: 16 }}>{posts?.username}</Text>
        </Flex>

How can I ensure the posts are correctly filtered by category and displayed without the “Posts not found” error?
Is there a more efficient way to handle the fetching and filtering of posts based on the selected category in React, considering best practices with Firestore?
Any insights or suggestions on what might be causing this issue and how to resolve it would be greatly appreciated.