in node js body.id doesnt working on server [duplicate]

When I access the server with postman, I get an error like a id not found or some thing like this.

Here is my code on get-routs.js :

<div class="main">
        <ul>${tasks
            .map((item) => {
                return `            <li data-id="${item.Id}">
                <span>
                    <lable>${item.Title}</lable>
                    <span class="${item.complited ? "com" : "uncom"}">${
                    item.complited ? "complited" : "in progress"
                }</span>
                    <button class="toggle-btn">toggle</button>
                    <button class="edit-btn" >edit</button>
                    <button class="delete-btn">delete</button>
                </span>

            </li>`;
            })
            .join("")}
        </ul>  

and here its post-route.js :

router.post("/toggle-task", (req, res) => {
    if (req.body.Id) {
        const task = Task.getTaskById(req.body.Id);
        console.log(req.body.Id);
        if (task) {
            task.complited = !task.complited;
            task.save();
            res.send("1");
        } else {
            res.status(404).send("<h1> task not foundd</h1>");
        }
    } else {
        res.status(400).send("error");
    }
});

export default router;

Despite in json file id number 2 exists post man gives error or doesn’t work

and here is my database :

[
    {
        "id": 1,
        "title": "Learn js",
        "complited": false
    },
    {
        "id": 2,
        "title": "Nodejs",
        "complited": false
    },
    {
        "id": 3,
        "title": "SQl",
        "complited": true
    }
]

Why onmessage never triggers in my BroadcastChannel?

I’m trying to use BroadcastChannel API but it seems that onmessage event is never triggered (or its handler is not working correctly).

const channel = new BroadcastChannel('foobar')

if (channel) {
  channel.onmessage = onMessage
}

export async function onMessage(event: MessageEvent) {
  alert('onMessage') // never triggers
}

export function post(message: Message) {
  alert('post') // works until this point
  channel?.postMessage(message)
}

In other file:

import * as BroadcastChannel from '@/utils/broadcastChannel/core'

BroadcastChannel.post('test')

Am I doing something incorrectly? Am I missing something?

Sorting an object by more than one value [duplicate]

I have a JSON file, that want to interrogate and return values.

On load the HTML page is populated with all the names.

persons = [
   {nationality: "GB",  code: 1004, initial: "J", surname: "Smith"},
   {nationality: "DEN", code: 1002, initial: "J", surname: "Smith"},
   {nationality: "GB",  code: 1003, initial: "A", surname: "Jones"},
   {nationality:" BEL", code: 1000, initial: "C", surname: "Down"}
];
    

This is how I have set it out so far:

As the user types in a surname in the Input box on each keyup it would query the filter the results from the data-attributes in the following way.

  1. surname > 2. initial > 3. nationality > 4. code.

So if a user starts to type in “Smith” the following result would appear in this order:

DEN. 1002, J. Smith. – would come first as the country name D is before E;
GB. 1004, J. Smith

The hierarchy of the filter would be:

Nationality (alphabetical order) > Surname (alphabetical Order) > Initial (alphabetical Order) > Code (numerical order).

I have seen a number of ways online to do this when wishing to filter and return the result on one object key but not on multiple ones.

This is something similar :
text.

Unable to group parts of the regex together to make the intended operator precedence explicit

The current regex /^(W)|([^a-zA-Z0-9_.]+)|(W)$/g is causing issues in SonarQube, and I need to group it properly. However, after grouping, it’s not working as expected.

The regex should meet the following conditions:

  1. Ensure there is a dot(s) at the start, end, or both ends of the string.
  2. In between, there can be anything except a-z, A-Z, 0-9, underscore, and dot (dots should not appear in the middle).

I tried this /^(.)|([^a-zA-Z0-9_.]+)|(.*.$)/g but i think it will again create an issue in SonarCube

How to catch routing errors when creating props for a component

I’m trying to catch errors that might occur when parsing route parameters to pass to a component. For instance, component A requires a URL object and the router creates the object from the route parameter before passing it to the component, e.g.

{
  path: "/test/:parameter",
  name: "test",
  component: Test,
  props: (route) => ({
    url: new URL(route.params.parameter),
  }),
},

Vue Router offers the onError function for catching certain kinds of errors and other places have suggested using Vue Router’s beforeEach. Unfortunately neither seems to be useful if an error is thrown while generating a route component’s props.

The v3 docs of onError suggest that this use case isn’t covered:

  • The error is thrown synchronously inside a route guard function;
  • The error is caught and asynchronously handled by calling next(err) inside a route guard function;
  • An error occurred when trying to resolve an async component that is required to render a route.

But it’s not exactly clear and it doesn’t seem very useful if this use case isn’t covered. So how would you do it?

MCVE

I’ve created a minimal example to demonstrate the behaviour. There are three links:

  1. “Valid” – should work fine
  2. “Invalid” – throws an exception when creating the props
  3. “Does not exist” – should throw an error because the route doesn’t exist

“Invalid” definitely throws an uncaught error (shown in the view), but neither 2. nor 3. write a log message into the console as expected.

New to react – how can I improve this code? [closed]

First of all, I started to learn React a month ago so bear with me. I’m here to learn from more experienced people.

In this Project, I made a simple table with filters (using Mantine) which is working as expected in terms of functionality but I am having noticeable lag when rendering the table (150 rows) – about 2s of 370ms. This is how profiler looks:
enter image description here

I tried to memo the rows but without any success. Can you guys take a look and point which part and how can I improve the performance and overall data flow of this app?

I would like to add that when I change rows to simple HTML rows the lag is almost zero, which would suggest that rendering those Mantine components are expensive and not the calculation of what to show. Appreciate all the comments.

Vue component not rendering in production build

I have this Filter code in which @vueforms/multiselect component is used:

Filter.vue

<template>
<div id="testm"></div>
</template>
<script lang="ts">
import {createApp} from 'vue';
import Multiselect from '@vueform/multiselect';
export default {
  name: 'DataFilter',
  async mounted() {
   
    let parent = document.getElementById("testm") as HTMLDivElement;
    const app = createApp({
      data() {
        return {

        };
      },
      methods: {

      },
      template: `
    <Multiselect

    />`,
      components: {
        Multiselect
      }
    });

    // if (app._container) {
    //   app.unmount();
    // }
    try {
      app.mount(parent);
      alert("mounted")
    } catch (error) {
      console.error('Error mounting app:', error);
    }
  },
}
</script>

Everything works with npm run dev while doing development.

But when I create a build using npm run build and deploy the dist folder. The component is not rendering at all like it’s not even there. The alerts and everything works fine.

The above is just a sample preview (skeleton) to explain of the Filter.vue some syntax errors might be there. Please ignore them.

If I add the component itself in the <template> like:

<template>
<Multiselect />
</template>

Then the component is rendered properly after build. I have spent many days on this issue, but not able to find solution (which works for me) regarding it.

Can you please tell what am I missing or how to fix this?

Get subfolders and files in a Box repository thru API and Apps Script

I’m trying to get the following in a Box folder with ID=1234567:

  • All subfolders and files (including files in the subfolders) of a particular folder
  • The name, URL and full folder path of each subfolder and file (ex. My folderFamilyPicture.jpeg where “My folder” is the one with ID=1234567)

I came upon this blog that provided a great starting point. Upon modifying the script, I was able to extract the item names and subfolders within “My folder”, but I’m not able to extract their URL, full folder path, and files within the different subfolders.

Here is part of the code where I’ve been having a headache:

function getFilesAndFolders() {
  var response = UrlFetchApp.fetch('https://api.box.com/2.0/folders/1234567/items?fields=name,type', {
    headers: {
      Authorization: 'Bearer ' + getBoxService_().getAccessToken(),
    },
  });

  var result = JSON.parse(response.getContentText());
  var items = result.entries;

  var filesAndFolders = [];

  for (var i = 0; i < items.length; i++) {
      filesAndFolders.push({ name: items[i].name, type:items[i].type, url:items[i].shared_link.url});
  }

  Logger.log(filesAndFolders);
}

In this resource, I saw this shared_link object that has the url field, but the script throws an error when I do items[i].shared_link.url. Also, I have no idea where to start with the full folder path. I saw this path_collection object but it doesn’t seem to have the field I need.

Any help is appreciated. Thanks!

sign up page for the multiple users using javascript

I want a sign-up page for multiple users in which when the user fills out the form and submits it then matches the data by email if the email is matched then match the password if the user is new then stores their data in local storage using an array and if the user exists in the array then alert to it welcome back in javascript and kindly code must be easy to understandable and the form contains only email password and submit button

Response Me Quickly

How can I display pdf file content with toolbar and sidebar in pdfjs-dist library

enter image description here
I want to show pdf content with toolbar as above, but it’s only show pdf, How can I configuration to show that.
that’s my step:

  1. I install pdfjs-dist: npm i pdfjs-dist
  2. my code:
    const pdfUrl = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';

    let pdfDoc = null,
        pageNum = 1,
        scale = 0.4,
        canvas = document.getElementById('pdf-canvas'),
        ctx = canvas.getContext('2d'),
        pageRendering = false,
        pageNumPending = null;

function showPdf() {
        pdfjsLib.getDocument(pdfUrl).promise.then(function(pdfDoc_) {
            console.log(pdfDoc_);
            pdfDoc = pdfDoc_;
            document.getElementById('page_count').textContent = pdfDoc.numPages;

            // Initial/first page rendering
            renderPage(pageNum);
        });
    }

    function renderPage(num) {
        pageRendering = true;
        pdfDoc.getPage(num).then(function(page) {
            const viewport = page.getViewport({scale: scale});
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            // Render PDF page into canvas context
            const renderContext = {
                canvasContext: ctx,
                viewport: viewport
            };
            const renderTask = page.render(renderContext);

            renderTask.promise.then(function() {
                pageRendering = false;
                if (pageNumPending !== null) {
                // New page rendering is pending
                renderPage(pageNumPending);
                pageNumPending = null;
                }
            });
        });
    }

html:

<button type="button" class="btn btn-outline-secondary" @click="showPdf();">PDF</button>

<div class="p-2 border">
    <canvas id="pdf-canvas"></canvas>
</div>

import:

import 'pdfjs-dist/build/pdf.min.mjs';
import * as pdfjsLib from 'pdfjs-dist/build/pdf.min.mjs';

pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;
window.pdfjsLib = pdfjsLib;

I try to customize a simple toolbar but take too much time, Somebody help..!
thanks

Testing Cross-Origin-Resource-Policy (CORP) with an iframe – not working as expected

I’m trying to test the Cross-Origin-Resource-Policy (CORP) header to ensure it’s functioning as expected on my site. I’ve configured the Cross-Origin-Resource-Policy header with the value same-origin on my server (e.g., mysite.co.in). The goal is to verify that content from my site cannot be embedded on a different domain.

Set CORP Header on My Site:

Applied the header Cross-Origin-Resource-Policy: same-origin on mysite.co.in.

Tested Embedding from a Different Domain:

Created a simple HTML page on a different domain like on codepen with the following code:

html

<iframe src="https://mysite.co.in" width="1500" height="600" style="border: none;" title="Testing CORP"></iframe>

Expected Outcome:

The iframe should not load, and I should see an error in the browser console or network tab indicating that the content was blocked due to CORP.

Actual Outcome:Site working fine on codepen’s iframe

How to add Date Range filter in Column header of ui table(sap.ui.table)

I am trying to add a Date Range filter in the column header of an sap.ui.table.Table. The solution I found in this SAP Community post seems to be outdated and doesn’t work with the latest SAP UI5 versions.

Is there an updated approach to implement a Date Range filter directly in the column header? Ideally, I would like to use sap.m.DateRangeSelection or a similar control that fits within the sap.ui.table.Column. How can this be achieved while ensuring compatibility with recent UI5 versions?

Any help or working example would be much appreciated!

I attempted to follow the solution from the SAP Community, which suggests overriding the filter bar with a custom control like sap.m.DateRangeSelection by manipulating the table’s filterProperty. Unfortunately, this approach didn’t seem to work, likely due to changes in how UI5 handles filtering in recent versions. I also tried adding a customData field to the column and setting it up manually, but it didn’t behave as expected within the column header.

What I was expecting:
I was expecting to add a sap.m.DateRangeSelection control in the column header filter area that allows users to select a date range, which would automatically filter the table data based on the selected date range. The filter should apply dynamically without any extra custom logic for handling the range comparison manually.

Is there an updated approach to implement a Date Range filter directly in the column header? Ideally, I would like to use sap.m.DateRangeSelection or a similar control that fits within the sap.ui.table.Column. How can this be achieved while ensuring compatibility with recent UI5 versions?

How to retrieve URL-info from URL’s listed in a local file?

I have a local file containing URL’s to Google Maps saved places.
These URL’s does not contain the GPS-position (latt/long), but if the URL is passed to a browser, then the URL is changed to something containing the GPS-pos. which I then want to extract and write back to a local file.
I am using javascript and/or HTML.
Anyone have a solution for how to do this?

I can access the local file from javascript using node.js and I can access the url from html.
But accessing the local file from a script within the html with script-code
const fs = required(‘fs’);
is not working.

Error “[Reanimated] Trying to access property ‘setValue'” when pinch to zoom in using react-native-pdf-light’s

I’m in a React Native project, currently trying to display a zoomable single page PDF file, I tried using <ZoomPdfView /> from the library react-native-pdf-light and the page is displayed, but this error shows up when trying pinch to zoom in. Any idea why this can happen and how to solve?

Attached in the link below is the screenshot to the error

https://github.com/user-attachments/assets/b81e8663-70cd-42eb-963a-971dfa2d5786

In the future I want to display all pages in ScrollView, so that the user can scroll through the entire PDF and zoom each page.

Any help or alternative to the outcome I was hoping for would be much appreciated,
thanks in advance.

Here is the code snippet:

const PdfViewer = ({ navigation }) => {

  const pdfRef = useRef();

  const uri = navigation.state.params.uri;
  const pageTitle = navigation.state.params.title;
  const initialPage = navigation?.state?.params?.initialPage;

  const sourceFile = useMemo(() => `${RNFS.DocumentDirectoryPath}/PDF-FILE.pdf`, []);

  const [isLoading, setIsLoading] = useState(true);
  const [localFilePath, setLocalFilePath] = useState(null);

  const onBackPressed = useCallback(() => {
    navigation.goBack();
  }, [navigation]);

  const renderLoadingIndicator = useMemo(() => (
    <View style={styles.loadingContainer}>
      <ActivityIndicator size='small' style={styles.activityIndicator} />
    </View>
  ), []);

  const onPdfLoadComplete = useCallback(() => {
    setIsLoading(false);
  }, [initialPage]);

  const downloadPdf = useCallback(async () => {
    try {
      const downloadResult = await RNFS.downloadFile({
        fromUrl: uri,
        toFile: sourceFile,
      }).promise;
      if (downloadResult.statusCode === 200) {
        setLocalFilePath(sourceFile);
      }
    } catch (error) {
      return Promise.resolve();
    }
  }, [uri, sourceFile]);

  useEffect(() => {
    downloadPdf();
  }, []);

  return (
    <SafeAreaView style={styles.safeAreaContainer}>
      <Navbar
        title={pageTitle}
        titleAlign='left'
        tintColor='black'
        backgroundColor='transparent'
        onPressBack={onBackPressed}
        compact
      />
      <View style={styles.container}>
        <ZoomPdfView
          ref={pdfRef}
          page={initialPage - 1}
          source={`file://${localFilePath}`}
          onLoadComplete={onPdfLoadComplete}
          trustAllCerts={Platform.OS === 'ios'}
          style={styles.pdfContainer}
        />
        {isLoading && renderLoadingIndicator}
      </View>
    </SafeAreaView>
  );
};

export default React.memo(PdfViewer);

Here are (some of) the libraries installed:

"react-native": "0.72.6",
"react-native-pdf-light": "^2.4.0",
"react-native-reanimated": "3.6.2",
"react-native-gesture-handler": "^2.13.4",

How to show image on page load instead of jQuery click function?

I use Sportlink javascript library and I’m trying to show logo of football clubs on the page. This library prints only links like:

https://binaries.sportlink.com/KNVB-production-DOCUMENT/95B8AF6A49636098D3F0709CB8D39A8C?expires=1725642258&sig=e915f414c03e1769fa25587ce6cd65b6ab99f048

So I’m trying to move this string to an img tag and I almost succeeded without any knowledge of javascript or jquery.

When I click the button I get a logo image, which I want. But I would like to show the logo on page load without clicking anything.

Example page: https://alcides.ineeditweb.nl/teams/test-team/

// Javascript library (embedded) code
   <div  
    data-article="programma"
    data-param-gebruiklokaleteamgegevens="NEE"
    data-param-eigenwedstrijden="JA"
    data-param-aantalregels="1"
    data-param-thuis="JA"
    data-param-uit="JA"
    data-label-thuisteamlogo="thuislogo"
    data-fields="thuisteamlogo" 
    ></div> 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <script>
    $(document).ready(function(){
    $("button").on( "click", function(){
    var a = $("div[data-label-thuisteamlogo='thuislogo']").text().replace("thuislogo", "");
    
    let img = document.createElement("img");
    img.src = a;
    document.getElementById("test").appendChild(img);
     });
     });
     </script>

     <button>Return value</button>

      <label id="test" style="width:60px" height="60px"></label>