Insert ignore attributes with missing columns

How can I insert a javascript/json object into a table and ignore missing columns? In my front end an object may have attributes that don’t correlate to columns in my table. I don’t want the insert operation to fail when that is the case. It should just insert the attributes that have a column and ignore the attributes that don’t have a column. Is that possible?

Setting symbol drag and drop limit

I have a table I created with chart.js in Modal. In this modal, I also have a symbol that I write the position in the chart in the tooltip both by drag and drop and by clicking. I want this symbol to be draggable only within certain pixel ranges. The values for the pixel equivalent should be taken from the database, converted to pixels and added to the limitation section. I was able to make this limitation for the x axis, but there is no limitation for the y axis. These are the Codes:

 function dragElement(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            elmnt.onmousedown = dragMouseDown;

            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                document.onmousemove = elementDrag;
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();

                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;

                var minX = calculatePixelValue(minFluidOutletTemp);
                var maxX = calculatePixelValue(maxFluidOutletTemp);
                var minY = calculatePixelValue(minAmbientTemp);
                var maxY = calculatePixelValue(maxAmbientTemp);

                var newX = elmnt.offsetLeft - pos1;
                var newY = elmnt.offsetTop - pos2;

                newX = Math.min(Math.max(newX, minX), maxX);
                newY = Math.min(Math.max(newY, minY), maxY);

                elmnt.style.left = newX + "px";
                elmnt.style.top = newY + "px";
                console.log("Sembolün X konumu (piksel):", newX);
                console.log("Sembolün Y konumu (piksel):", newY);
                updateTooltipPosition(elmnt);
            }

            function closeDragElement() {
                document.onmouseup = null;
                document.onmousemove = null;
            }
            
            function calculatePixelValue(value) {
                var chartInstance = myChart;
                var chartArea = chartInstance.chartArea;
                var chartWidth = chartArea.right - chartArea.left;
                var chartHeight = chartArea.bottom - chartArea.top;

                var normalizedValue = (value - xAxisMin) / (xAxisMax - xAxisMin);
                var pixelValue = chartArea.left + normalizedValue * chartWidth;
                return pixelValue;
            }
        }

How can I take the values from the database for the y-axis, convert them to pixels and set the limit correctly?

How to apply a theme generated from Material 3 Theme builder website to the project in Angular 17.2.0?

I am using Angular 17.2.0, I wish to apply custom theming to my Material 3 UI (Experimental). I generated a theme from https://m3.material.io/theme-builder. I exported the theme which gives me a bunch of CSS files, I included the theme.css file which @imports all the other files. I could not find any documentation in relation to how to use user-defined theme, all the documentation is regarding how to use pre-defined palettes or to set primary, accent color for material 2.

Following is the code of my current styles.scss file:

@use '@angular/material' as mat;
@use '@angular/material-experimental' as matx;

$dark-theme: matx.define-theme((
  color: (
    theme-type: dark,
    primary: matx.$m3-green-palette
  ),
  density: (
    scale: -1
  )
)); 

*{
  @include mat.all-component-themes($dark-theme);
}

html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

I tried including the theme.css file which @imports all the other files, searched for documentation on m3.material.io and https://material.angular.io/ but couldn’t come up with an answer to my problem.

edit/insert tinymce image return blob path i don’t want this blob path

here is my JS tinymce code in which I get image URL response but when i edit/insert crop image its return blob image i don’t want this path how can i fix this?

tinymce.init({
selector: ‘textarea#fundraise_description’,
plugins: ‘anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed linkchecker a11ychecker tinymcespellchecker permanentpen powerpaste advtable advcode editimage advtemplate mentions tableofcontents footnotes mergetags autocorrect typography inlinecss image code fontfamily’,
// toolbar: ‘undo redo | link image | code’,
toolbar1: ‘link image | undo redo | styles | fontfamily | fontsize | bold italic underline strikethrough blockquote subscript superscript | alignleft aligncenter alignright alignjustify | indent outdent | wordcount’,
// toolbar2: ‘table tablecellprops tablecopyrow tablecutrow tabledelete tabledeletecol tabledeleterow tableinsertdialog tableinsertcolafter tableinsertcolbefore tableinsertrowafter tableinsertrowbefore tablemergecells tablepasterowafter tablepasterowbefore tableprops tablerowprops tablesplitcells tableclass tablecellclass tablecellvalign tablecellborderwidth tablecellborderstyle tablecaption tablecellbackgroundcolor tablecellbordercolor tablerowheader tablecolheader’,
image_title: true,
automatic_uploads: true,
convert_urls: false,
file_picker_types: ‘image’,
file_picker_callback: function (cb, value, meta) {
const input = document.createElement(‘input’);
input.setAttribute(‘type’, ‘file’);
input.setAttribute(‘accept’, ‘image/*’);

    input.addEventListener('change', (e) => {
        const file = e.target.files[0];
        const reader = new FileReader();
        //console.log(file.name);
        var fd = new FormData();
        fd.append('filetype', meta.filetype);
        fd.append('file', file);
        fd.append('action', 'upload_fundaraiser_image');
        console.log(fd);
        jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>', 
        type: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        success: function(response) {
            //console.log("RESPONSE===>", response)
                  if (response.startsWith('ImageURLFailed')) {
                        alert('Failed to upload image. Please try again.');
                    } else {
                      // Remove the last character if it is '0'
                    reader.addEventListener('load', () => {
                        // Note: Now we need to register the blob in TinyMCEs image blob
                        // registry. In the next release this part hopefully won't be
                        // necessary, as we are looking to handle it internally.
                    
                        //Pass the returned URL to the callback function
                        const editedImageUrl = response;
                        cb(editedImageUrl, { title: file.name });

                        });
                        reader.readAsDataURL(file);
                    }
        },
        error: function(xhr, status, error) {
            alert('HTTP Error: ' + xhr.status);
        }
    });
    });
    input.click();
    },

    images_upload_handler: function(blobInfo, success, failure) {
       if (blobInfo) {
        console.log(blobInfo.blob());
        console.log(blobInfo.filename()); 
    }
});

<div class="col-md-12">
    <textarea id="fundraise_description"><?php echo $content; ?></textarea>
</div>

How to convert Unicode character to symbol/special character in JavaScript [duplicate]

I have a sentence ‘Hello u0028 Hi u0029’ that contains few unicode character.My requirement is if any sentence contains unicode character it will be converted into special character for ex- ‘Hello ( Hi )’.I have already tried but it is not working.Please find below code

1.html

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
    var str= 'Hello \u0028 Hi \u0029';
   var res= str.replace(/&#([0-9]{1,4});/gi, function(match, numStr) {
        var num = parseInt(numStr, 10); // read num as normal number
        return String.fromCharCode(num);
    })
    console.log(res);
</script>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

Difficulty with Responsiveness: Details and Image Grid Layout

I’m encountering difficulties achieving the desired responsiveness for a grid layout that includes details and an image. On desktop screens, the layout appears as intended, with the details displayed on the left and the image on the right. However, on mobile screens, the image appears below the details, which is not the desired behavior.

Here’s the code structure I’m working with:



import React from 'react';
import {
  Box, Paper, useMediaQuery, useTheme, Typography, Grid, Container,
} from '@mui/material';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormGroup from '@mui/material/FormGroup';
import { Link } from 'react-router-dom';
import LocationOnIcon from './SVGiCON';

export const CarInfo: React.FC = () => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  const [state, setState] = React.useState({
    gilad: false,
    jason: false,
    antoine: false,
  });

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setState({
      ...state,
      [event.target.name]: event.target.checked,
    });
  };

  const { gilad, jason, antoine } = state;
  const [value, setValue] = React.useState<number | null>(2);

  return (
    <Container>
      <Box
        display="flex"
        flexDirection="column"
        alignItems="center"
        justifyContent="center"
        minHeight="100vh"
      >
        <Paper
          elevation={3}
          sx={{
            p: '1.5rem', // Use rem units
            borderRadius: '1.25rem', // Use rem units
            textAlign: 'center',
            maxWidth: isMobile ? '100%' : 'xl',
            width: '68.75rem', // Use rem units
            backgroundColor: 'grey !important',
            overflow: 'hidden', // Ensure the container doesn't overflow
          }}
        >
          <Grid container spacing={2} alignItems="center" justifyContent="center">
            <Grid item xs={12} md={6} style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
              {/* Details */}
              <Typography variant="h4" gutterBottom color={'white'}>
                Car Title
              </Typography>

              <Typography variant="body1" align="left">
                Собственик{' '}
                <Link to="/home" style={{ textDecoration: 'none', marginLeft: '0.625rem' }}>
                  <span style={{
                    color: 'black', backgroundColor: 'green', borderRadius: '1.25rem', padding: '0.625rem',
                  }}>
                    Александър Иванов
                  </span>
                </Link>
              </Typography>

              <Typography variant="body1" align="left" style={{ marginLeft: '2.5rem', marginTop: '1.25rem', marginBottom: '1.25rem' }}>
                <LocationOnIcon style={{ marginRight: '0.625rem', width: '0.9375rem', height: '0.9375rem' }} />
                Костинброд, София-област
              </Typography>

              {/* Other details */}
              <Typography variant="body1" align="left" style={{ marginLeft: '2.5rem' }}>
                <LocationOnIcon style={{ marginRight: '0.625rem', width: '0.9375rem', height: '0.9375rem' }} />
                Бензин
              </Typography>

              <Typography variant="body1" align="left" style={{ marginLeft: '2.5rem' }}>
                <LocationOnIcon style={{ marginRight: '0.625rem', width: '0.9375rem', height: '0.9375rem' }} />
                Черен
              </Typography>

              <Typography variant="body1" align="left" style={{ marginLeft: '2.5rem' }}>
                <LocationOnIcon style={{ marginRight: '0.625rem', width: '0.9375rem', height: '0.9375rem' }} />
                2022 г.
              </Typography>

              <Typography variant="body1" align="left" style={{ marginLeft: '2.5rem' }}>
                <LocationOnIcon style={{ marginRight: '0.625rem', width: '0.9375rem', height: '0.9375rem' }} />
                90 000 км
              </Typography>

              <FormGroup style={{ marginLeft: '2.5rem', marginTop: '0.6875rem' }}>
                <FormControlLabel
                  style={{ marginBottom: '-0.625rem', color: "black" }}
                  control={
                    <Checkbox
                      checked={gilad}
                      onChange={handleChange}
                      name="gilad"
                      size='small'
                      style={{ color: 'black' }} />
                  }
                  label="Реален пробег"
                />
                <FormControlLabel
                  style={{ color: "black" }}
                  control={
                    <Checkbox checked={jason}
                      onChange={handleChange}
                      name="jason"
                      size='small'
                      style={{ color: 'black' }} />
                  }
                  label="Първи собственик"
                />
              </FormGroup>
            </Grid>

            <Grid item xs={12} md={6}>
              {/* Photo */}
              <div style={{ maxWidth: '100%', overflow: 'hidden' }}>
                <img
                  src="https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
                  alt="Car"
                  style={{
                    width: '100%', // Ensures the image is responsive
                    height: 'auto', // Ensures aspect ratio is maintained
                    display: 'block', // Ensures the image doesn't have any extra spacing issues
                  }}
                />
              </div>
            </Grid>
          </Grid>
        </Paper>
      </Box>
    </Container>
  );
};

export default CarInfo;


This is how it looks right now on the phone:
This is how it looks right now on the phone

This is how it ПКЯШ looks on the phone:

This is how it MUST looks on the phone

I’ve tried adjusting the grid layout and applying responsive styles, but the image continues to appear below the details on mobile screens. I’m aiming for a layout where both the details and the image remain side by side on larger screens and stack appropriately on smaller screens.

Any suggestions or insights on how to achieve the desired responsiveness for this grid layout would be greatly appreciated.

Thank you!

how to delete array data according to a certain index in reactjs

I want to try deleting the technologies data according to the index using the handleDeleteTechnology function but when I try to delete it and it works if I see the data in the data, but in the UI what is deleted is always the last index even though I want to delete the first index.

const handleDeleteTechnology = (index) => {
    const updatedTechnologies = [...technologies];
    updatedTechnologies.splice(index, 1);
    setTechnologies(updatedTechnologies);

    const updatedDetailTechData = [...detailTechData];
    updatedDetailTechData.splice(index, 1);
    setDetailTechData(updatedDetailTechData);

    return setFilesTech(prevFilesTech => {
      const updatedFilesTech = [...prevFilesTech];
      updatedFilesTech.splice(index, 1);
      return updatedFilesTech;
    });
  };

        {technologies.map((tech, index) => (
          <div className='flex' key={index} index={index}>
            <div className='relative'>
              <FaCircleMinus size={25} className='absolute -top-2 -left-2 text-red-600' onClick={() => handleDeleteTechnology(index)} />
            </div>
            <UploadTechnology
              index={index}
              technology={tech}
              onImageChange={(index, imageUrl) => handleImageChange(index, imageUrl)}
            />
          </div>
        ))}

I’ve tried searching on Google or chatgpt but still haven’t found this problem

Javascript function to form then submit [closed]

I’m having a slight issue with my code. I am a VERY basic user and so I’m struggling a great deal. What I am trying to achieve, is a button on my website, that gets a geolocation with “getLocationConstant()” puts the geolocation into a form, and then sends a text message via a .php script.

Currently the Geolocation is populating the form, but when submit, the form is blank? I can only assume that is because the Javascript takes a moment to get the coordinates by which time the form has already submitted with no data. Here is my code:

The process/logic I’m currently using is:

  1. Submit Button -> Which Calls the JavaScript Geolocation and populated to a form.
  2. JavaScript which then runs a .php script with EventListener, preventing Default settings.

The Geolocation is populated in the form, however the data in the form is not sent across to the PHP script for some reason? I can’t give any further information on this issue, as this is the issue as I know it and the purpose for me posting here. Thanks in advance 🙂

<script type="text/javascript">

    function getLocationConstant() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        } else {
            alert("Your browser or device doesn't support Geolocation");
        }
    }

    // If we have a successful location update
    function onGeoSuccess(event) {
        document.getElementById("message").value = "Hello, someone has scanned <?php echo $petname1 ?>'s tag. See the GPS location below: https://www.google.com/maps/place/" + event.coords.latitude + "," + event.coords.longitude;

    }

    // If something has gone wrong with the geolocation request
    function onGeoError(event) {
        alert("Error code " + event.code + ". " + event.message);
    }
    
</script>
              
            <form id="sendmessage">
            <textarea type="text" name="number" id="number" hidden><?php echo $phone ?></textarea>
            <input type="text" id="message" name="message" value="">
            <button type="submit" onclick="getLocationConstant()">Send GPS location to the owner</button>
            </form>
            

            
            
            
            <script>
            const sendmessage = document.getElementById("sendmessage");
            
            sendmessage.addEventListener("submit", (e) => {
                e.preventDefault();
                
                const request = new XMLHttpRequest();
                
                request.open("post", "send.php");
                request.onload = function () {
                    console.log(request.responseText);
                }
                
                request.send(new FormData(sendmessage));
                
                
            });
            
            </script>

I’ve tried EVERYTHING I possibly can with VERY LIMITED knowledge.

Sequelize Error: Named bind parameter “$amount” has no value in the given object

This is my sequelize code:

const insertQuery = `
    INSERT INTO transaction (amount, company_id, user_id, journal_id, type, account_id, plaid_transaction_id)
    SELECT $amount, $company, $user_id, $journal_id, $type, $account_id, $plaid_transaction_id
    WHERE NOT EXISTS (
      SELECT 1 FROM transaction WHERE plaid_transaction_id = $plaid_transaction_id
    )
    RETURNING id, amount, company_id, user_id, journal_id, type, account_id, plaid_transaction_id;
  `;


const bindParams: any = transactionData.map(({ amount, company_id, user_id, journal_id, type, account_id, plaid_transaction_id }) => ({
  amount,
  company: company_id,
  user_id,
  journal_id,
  type,
  account_id,
  plaid_transaction_id,
}));

 // Generate the SQL query with interpolated bind parameters
 const resolvedQuery = insertQuery.replace(/$w+/g, match => {
  const paramName = match.substring(1); // Remove the $ sign
  const paramValue = bindParams[0][paramName]; // Assuming the first element contains all params
  return sequelize.escape(paramValue); // Ensure proper escaping
});

console.log("Resolved SQL Query:", resolvedQuery);

 

  const insertedRows = await sequelize.query(insertQuery, {
    bind: bindParams,
    type: QueryTypes.INSERT,
    transaction: transactionObj,
  });

  return insertedRows;

I’m getting error: Named bind parameter “$amount” has no value in the given object.

This is my resolved sql query (which verifies that the data I’m passing is correct):

INSERT INTO transaction (amount, company_id, user_id, journal_id, type, account_id, plaid_transaction_id)
    SELECT 89.4, 42, 48, 293, 'debit', 1858, 'rkA3lL4bxxf4Jvv9x4gaibxXQjlaLlC7kb4mL'
    WHERE NOT EXISTS (
      SELECT 1 FROM transaction WHERE plaid_transaction_id = 'rkA3lL4bxxf4Jvv9x4gaibxXQjlaLlC7kb4mL'
    )
    RETURNING id, amount, company_id, user_id, journal_id, type, account_id, plaid_transaction_id;

Issue with Sorting Array of Objects in JavaScript [closed]

I’m trying to sort an array of objects based on a specific property, but I’m encountering some difficulties. Here’s a simplified version of my data structure:

const data = [
  { id: 1, name: "John" },
  { id: 2, name: "Alice" },
  { id: 3, name: "Bob" }
];

I would like to sort this array of objects alphabetically based on the ‘name’ property. I’ve tried using the array.sort() method, but I seem to be missing something. Here’s the code I’ve used for sorting:

data.sort((a, b) => {
  return a.name.localeCompare(b.name);
});

However, the sorting doesn’t seem to work as expected. Can someone please point out what I might be doing wrong and provide a solution for correctly sorting this array of objects based on the ‘name’ property?

Any help or insights would be greatly appreciated. Thank you!

react-i18next language is not set during tests with vitest

Language is not set during tests with vitest. In a dependency I import, this code exists:

function useI18N() {
  var _useTranslation = reactI18next.useTranslation(),
      t = _useTranslation.t,
      language = _useTranslation.i18n.language;

  if (language !== 'nb' && language !== 'en') {
    throw Error('Language must be either nb or en.');
  }

  return t;
}

function withI18n(Component) {
  return function WrappedComponent(props) {
    var t = useI18N();
    return /*#__PURE__*/React__default["default"].createElement(Component, _extends({}, props, {
      i18n: t
    }));
  };
}

This code throws throw Error('Language must be either nb or en.'); when testing using vitest. It does not throw for building with vite nor with the previous test runner jest (with practically same config).

That code is wrapping a component that is consumed by several components up until the file I am testing, which is using this:


export const renderWithI18NContext = (
  component: ReactNode,
  organisation?: Organisation,
  locale = 'nb'
) => {
  return render(componentWithI18NContext(component, organisation, locale));
};

const componentWithI18NContext = (
  …
) => {
  store.dispatch(…);

  i18n.changeLanguage(locale);

  return (
    <Provider store={store}>
      {/* @ts-ignore */}
      <MemoryRouter>
        <SWRConfig value={{ dedupingInterval: 0 }}>
          <Some.Provider value={something}>
            {component}
          </Some.Provider>
        </SWRConfig>
      </MemoryRouter>
    </Provider>
  );
};

With an import i18n that looks like this:

use(initReactI18next).init({
  lng: 'nb',
  fallbackLng: 'nb',
  resources: {
    nb: {
      translation: {
        …
      }
    },
    en: {
      translation: {
        …
      }
    }
  },
  interpolation: {
    escapeValue: false // not needed for react as it escapes by default
  }
});

export default i18n;

Which is consumed like this:

it('should pass', async () => {
  renderWithI18NContext(
    <ComponentTestContainer>
      …
      component={<ComponentToTest {...props} />}
    />
  );

  expect(…);
});

I’ve narrowed it down to react-i18next is not picking up language, i.e., that use(initReactI18next).init({…}) is not called, or something..

In Javascript event.key not returning keypresses for hangul characters in console.log

I have been having trouble with Hangul (KO) character input on an html5 webpage that uses Ajax. console.log will not log the keystrokes for Hangul, but it will log English keystrokes. The code that is supposed to show what I type is as follows:

document.getElementById('userText').addEventListener('keydown', function(event) {

  console.log('410-Key pressed: ', event.key);

.... lot's of other code
}

How can I get the key events for Hangul characters instead of just the word ‘process’?

This problem occurs on both Firefox and chrome browsers on the desktop.

The <html lang="ko"> tag is present.

The typing is taking place in an element of type textarea
<textarea id="userText" lang="KO"></textarea>.

This is part of a larger problem where, on android mobile devices, the initial Hangul character typed is shown as the individual key-presses while subsequent Hangul characters are properly assembled and shown as syllable characters.

I was expecting to see the character typed, whether English or Korean. In the case of Korean I was expecting to see the individual vowels and consonant characters and then the syllable character.

Why my Node JS API doesn’t work in live server while perfectly working in PostMan?

I have a node js API to get all users from mongoDB and is hosted in AWS elasticBean.

However the api works perfectly fine in postman but not when integrated in React Native or React webapp.

I even have add CORS in the api.

Below is the Code for the API:

Modal:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
 
const usersSchema = new Schema({
  mobile: String,
  password: String,
  fullName: String,
  gender: String,
  email: String,
  position: String,
  organization: String,
  skills: [],
  location: String,
  socialLink: String,
  story: String,
  headline: String,
  industry: String,
  experience: String,
  profilePic: String,
  createdAt: {
    type: Date,
    default: Date.now,
  },
});
 
module.exports = mongoose.model("users", usersSchema);

Service:

const usersModel = require("../models/user.modal");

exports.userGetAllService = async () => {
  return await usersModel.find();
};

Controller:

const { MongoClient, ObjectId } = require('mongodb');
const { userGetAllService } = require("../services/user.service");

 exports.userGetAllController = async (req, res) => {
    try {
      const userGetAllExport = await userGetAllService();
      res.json({ data: userGetAllExport, status: "success", api:"GetAllUsers" });
     } catch (err) {
      res.status(500).json({ error: err.message });
    }
  };

Route:

const express = require("express");
const { userGetAllController, userGetListController, userGetByIdController, userPasswordUpdateController } = require("../controllers/user.controller");
 
const router = express.Router();
 
router.route("/all/").get(userGetAllController);
router.route("/list/:id").get(userGetListController);
router.route("/:id").get(userGetByIdController);
router.route("/password/").put(userPasswordUpdateController);
 
module.exports = router;

APP:

const connectToDatabase = require("./db");
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();

const port = process.env.PORT || 3000;
const secretKey = process.env.SECRET_KEY;

const fileUpload = require('express-fileupload');
const AWS = require('aws-sdk');
AWS.config.update({ region: 'ap-south-1' })

app.use(fileUpload({
  limits: { fileSize: 50 * 1024 * 1024 },
}))

const userRouter = require("./routes/user.route");

app.use(express.json());
connectToDatabase();

app.use("/api/user", userRouter);

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next(); 
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

module.exports = app;

The API i’m calling ‘http://api.levelon.in/api/user/all’
which get all user as expected in POSTMAN,

but when tried with React or Native R, return “Axios Network Error”

Please explain why and how to resolve it.

Any help is greatly appreciated..

How do I reapply my HTML mouse events after replacing code with code using innerHTML?

A certain part of the body of my code has HTML onmousehover events to show hidden DIVs on hover. When I replace that code using innerHTML on mouse click with an identical block of code because I’m supposed to simulate moving to another webpage and back with just 1 webpage, the hover events no longer work. How do I reapply the hover events? Below is the innerHTML code I use, onclick=retract() on the button I click to execute the function.

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    
    <style>
    
        #subhead {
            font-family: Monotype Corsiva;
            font-size: 1.3vw;
        }
        
        #headhead {
            font-family: Segoe Script;
            font-size: 1.5vw;
        }
        
        body {
            background-image: url(bg.jpeg);
            background-size: cover;
        }
        
        .menuItem {
            font-family: Segoe Script;
            font-weight: bold;
            font-size: 1.2vw;
        }
    
        #hide1 {
            display: none;
        }
        #hide2 {
            display: none;
        }
        #hide3 {
            display: none;
        }
        #hide4 {
            display: none;
        }
    
        .menuBanner {
            border: 5px double;
            height: 70vh;
            display: flex;
            flex-direction: column;
            padding-left: 50px;
        }
        
        .hoverClick {
            cursor: pointer;
        }
        
        .topDiv {
            height: 10%;
        }
        
        .middleDiv {
            height: 68%;
        }
        
        .bottomDiv {
            height: 17%;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            align-content: center;
            background-color: #E4E4E4;
            // border: 1px solid;
        }
        
        .resetButtonClass {
            margin-left: 52vw;
            margin-top: auto;   
        }
        
        #resetButtonID {
            border: solid;
            width: 7vw;
            padding: 5px;
            text-align: center;
            background-color: black;
            font-size: 0.8vw;
            cursor: pointer;
        }
        
        .banner1 {
            background-color: #FDF9F9;
        }
        
        .menuImage {
            background-repeat: no-repeat;
        }
        
        br {
            line-height: 1vh;
        }
        
    </style>
    
</head>

<body id="fullReset">
    
    <!-- HEADER BLOCK -->
    <div id="headerFourElement" class="container-fluid p-4 text-black" style="background-color: #d1ccc9;">
        <div class="row">
            <div class="col">
                <h3 id="subhead">BEST of the MERIDIAN</h3>
                <h2 id="headhead">Restaurant Guide</h2>
            </div>
            <div class="col resetButtonClass text-white" onclick="retract()">
                <p id="resetButtonID">Main Menu</p>
            </div>
        </div>
    </div>
    
    <!-- MENU BLOCK -->
    <div id="baseMenu" class="container mt-5">
        <div class="row gx-5">
            <!-- COLUMN ONE -->
            <div class="col">
                <div id="testHover1" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(0)">
                    <p class="menuItem topDiv">Primavera</p>
                    <div class="middleDiv menuImage" style="background-image: url(aglio.jpg);"></div>
                    <div id="hide1" class="bottomDiv">
                        <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Going for the classics? Primavera has pasta!</p>
                        <p style="font-size: 0.8vw; font-family: Monotype Corsiva;">▶ Show More</p>
                    </div>
                 </div>
            </div>
            <!-- COLUMN TWO -->
            <div class="col">
                 <div id="testHover2" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(1)">
                    <p class="menuItem topDiv">La Bulesca</p>
                    <div class="middleDiv menuImage" style="background-image: url(truffle.jpeg);"></div>
                    <div id="hide2" class="bottomDiv">
                        <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Can't go wrong with genuine Italy pizza!</p>
                        <p style="font-size: 0.8vw; font-family: Monotype Corsiva;">▶ Show More</p>
                    </div>
                 </div>
            </div>
            <!-- COLUMN THREE -->
            <div class="col">
                 <div id="testHover3" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(2)">
                    <p class="menuItem topDiv">Il Messagero</p>
                    <div class="middleDiv menuImage" style="background-image: url(caprese.jpg);"></div>
                    <div id="hide3" class="bottomDiv">
                        <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Vegetarian? We got you covered! Have some Caprese, some Friarelli.</p>
                        <p style="font-size: 0.8vw; font-family: Monotype Corsiva;">▶ Show More</p>
                    </div>
                 </div>
            </div>
            <!-- COLUMN FOUR -->
            <div class="col">
                 <div id="testHover4" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(3)">
                    <p class="menuItem topDiv">Casa Oliva</p>
                    <div class="middleDiv menuImage" style="background-image: url(prosciutto.png);"></div>
                    <div id="hide4" class="bottomDiv">
                        <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Something light for the night! Casa Oliva is your best bet.</p>
                        <p style="font-size: 0.8vw; font-family: Monotype Corsiva;">▶ Show More</p>
                    </div>
                 </div>
            </div>
        </div>
    </div>
    
    <script>
        
        <!-- GETTING ELEMENTS -->
        <!------------------------------------------------------------------------->
        const elem1 = document.getElementById('testHover1');
        const elem2 = document.getElementById('testHover2');
        const elem3 = document.getElementById('testHover3');
        const elem4 = document.getElementById('testHover4');

        const hiddenDiv1 = document.getElementById('hide1');
        const hiddenDiv2 = document.getElementById('hide2');
        const hiddenDiv3 = document.getElementById('hide3');
        const hiddenDiv4 = document.getElementById('hide4');
        
        <!-- MOUSEOVER EVENTS -->
        <!------------------------------------------------------------------------->
        elem1.addEventListener('mouseover', function handleMouseOver() {
            hiddenDiv1.style.display = 'block';
        });
        elem2.addEventListener('mouseover', function handleMouseOver() {
            hiddenDiv2.style.display = 'block';
        });
        elem3.addEventListener('mouseover', function handleMouseOver() {
            hiddenDiv3.style.display = 'block';
        });
        elem4.addEventListener('mouseover', function handleMouseOver() {
            hiddenDiv4.style.display = 'block';
        });
        
        <!-- MOUSEOUT EVENTS -->
        <!------------------------------------------------------------------------->
        elem1.addEventListener('mouseout', function handleMouseOut() {
            hiddenDiv1.style.display = 'none';
        });
        elem2.addEventListener('mouseout', function handleMouseOut() {
            hiddenDiv2.style.display = 'none';
        });
        elem3.addEventListener('mouseout', function handleMouseOut() {
            hiddenDiv3.style.display = 'none';
        });
        elem4.addEventListener('mouseout', function handleMouseOut() {
            hiddenDiv4.style.display = 'none';
        });
        
        <!-- MOUSE CLICK EVENTS -->
        <!------------------------------------------------------------------------->
        function retract() {
            const replaceDiv = document.getElementById('baseMenu').innerHTML = `
            <div class="row gx-5">
                <div class="col">
                    <div id="testHover1" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(0)">
                        <p class="menuItem topDiv">Primavera</p>
                        <div class="middleDiv menuImage" style="background-image: url(aglio.jpg);"></div>
                        <div id="hide1" class="bottomDiv">
                            <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Going for the classics? Primavera has pasta!</p>
                        </div>
                     </div>
                </div>
                <div class="col">
                     <div id="testHover2" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(1)">
                        <p class="menuItem topDiv">La Bulesca</p>
                        <div class="middleDiv menuImage" style="background-image: url(truffle.jpeg);"></div>
                        <div id="hide2" class="bottomDiv">
                            <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Can't go wrong with genuine Italy pizza!</p>
                        </div>
                     </div>
                </div>
                <div class="col">
                     <div id="testHover3" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(2)">
                        <p class="menuItem topDiv">Il Messagero</p>
                        <div class="middleDiv menuImage" style="background-image: url(caprese.jpg);"></div>
                        <div id="hide3" class="bottomDiv">
                            <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Vegetarian? We got you covered! Have some Caprese, some Friarelli.</p>
                        </div>
                     </div>
                </div>
                <div class="col">
                     <div id="testHover4" class="p-3 menuBanner hoverClick banner1 text-center" onclick="expand(3)">
                        <p class="menuItem topDiv">Casa Oliva</p>
                        <div class="middleDiv menuImage" style="background-image: url(prosciutto.png);"></div>
                        <div id="hide4" class="bottomDiv">
                            <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Something light for the night! Casa Oliva is your best bet.</p>
                        </div>
                     </div>
                </div>
            </div>
            `;
        }
                    
        function expand(index) {
            if (index == 0) {
                const replaceDiv = document.getElementById('baseMenu').innerHTML = `
                <div class="row gx-5">
                    <div class="col">
                        <div id="testHover1" class="p-3 menuBanner banner1 text-center" onclick="expand(0)">
                            <p class="menuItem topDiv">Primavera</p>
                            <div class="middleDiv menuImage" style="background-image: url(aglio.jpg);"></div>
                            <div id="hide1" class="bottomDiv">
                                <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Going for the classics? Primavera has pasta!</p>
                            </div>
                         </div>
                    </div>
                </div>
                `;
            } else if (index == 1) {
                const replaceDiv = document.getElementById('baseMenu').innerHTML = `
                <div class="row gx-5">
                    <div class="col">
                        <div id="testHover2" class="p-3 menuBanner banner1 text-center" onclick="expand(1)">
                            <p class="menuItem topDiv">La Bulesca</p>
                            <div class="middleDiv menuImage" style="background-image: url(truffle.jpeg);"></div>
                            <div id="hide2" class="bottomDiv">
                                <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Can't go wrong with genuine Italy pizza!</p>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            } else if (index == 2) {
                const replaceDiv = document.getElementById('baseMenu').innerHTML = `
                <div class="row gx-5">
                    <div class="col">
                        <div id="testHover3" class="p-3 menuBanner banner1 text-center" onclick="expand(2)">
                            <p class="menuItem topDiv">Il Messagero</p>
                            <div class="middleDiv menuImage" style="background-image: url(caprese.jpg);"></div>
                            <div id="hide3" class="bottomDiv">
                                <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Vegetarian? We got you covered! Have some Caprese, some Friarelli.</p>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            } else if (index == 3) {
                const replaceDiv = document.getElementById('baseMenu').innerHTML = `
                <div class="row gx-5">
                    <div class="col">
                        <div id="testHover4" class="p-3 menuBanner banner1 text-center" onclick="expand(3)">
                            <p class="menuItem topDiv">Casa Oliva</p>
                            <div class="middleDiv menuImage" style="background-image: url(prosciutto.png);"></div>
                            <div id="hide4" class="bottomDiv">
                                <p style="font-size: 0.9vw; font-family: Monotype Corsiva;"><br>Something light for the night! Casa Oliva is your best bet.</p>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            }
            
        }
        
    </script>
    
</body>

Sentry not initializing in Vue 3 custom components

I’m getting the following warning when trying to connect sentry in my vue 3 custom web components

[@sentry/vue]: Misconfigured SDK. Vue specific errors will not be captured. Update your `Sentry.init` call with an appropriate config option: `app` (Application Instance – Vue 3) or `Vue` (Vue Constructor – Vue 2)

This is my applications entry point

// Custom Elements 
export function registerComponent1() {
  customElements.define('name1', defineCustomElement(Component1));
}
export function registerComponent2() {
  customElements.define('name2', defineCustomElement(Component2));
}
export function registerComponent3() {
  customElements.define('name3', defineCustomElement(Component3));
}


export const defineCustomElement = (component) => {
  
  return VueDefineCustomElement({
    setup() {
      const inst = getCurrentInstance();

      Sentry.init({
        app: inst.appContext.app,
        dsn: '...'
        integrations: [Sentry.browserTracingIntegration()],
        // Performance Monitoring
        tracesSampleRate: 1.0, //  Capture 100% of the transactions
      });

      return () => h(component);
    },
  });
};

I tested the connect by created a button like such and it seems to be working

function sendSentryData() {
  Sentry.captureMessage('Button clicked');
}

 <button @click="sendSentryData">Click me</button>

So what’s causing this issue, like I want to track when networks requests fail, vue or non-vue specific issues. Also will implementing it like such initialize Sentry three times?

passed application instance to Sentry.init by

getCurrentInstance().appContext.app;