{mern stack} Help my Web App is not connecting

I have been trying to learn how to use the MERN stack by creating a simple web app. I even downloaded multiple already completed projects from GitHub and the one problem i keep happening in EVERY project.

It returns a response of Cannot POST /record/add

Please please someone help, ill send any other info you need to find the problem this one particular isnt my project it is an example i found online

Error in Code

Mandatory console log? [duplicate]

function removeExtraSpace(input) {
  const pattern = /(?:<p><br></p>)+$|(<p> *</p>)+$/g;
  while(pattern.test(input.trimEnd()) == true){
      input = input.trimEnd().split(pattern)[0]
  }
  return input;
}

console.log(removeExtraSpace("<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "));

Input example:

"<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "

Expected output:

"<p>test</p><p>test2</p>"

Returns:

"<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p>"

But if I add a console log to my loop, it starts to work. What am I bastardizing here?

function removeExtraSpace(input) {
  const pattern = /(?:<p><br></p>)+$|(<p> *</p>)+$/g;
  while(pattern.test(input.trimEnd()) == true){
      input = input.trimEnd().split(pattern)[0]
      console.log(pattern.test(input.trimEnd()))
  }
  return input
} 

console.log(removeExtraSpace("<p>test</p><p>test2</p><p><br></p><p><br></p><p></p><p> </p><p>  </p> "));

Web scraping based on the class name

I’m doing web scraping on google maps website to get the distance between two points.
the scraping is based on the className (because the attribute doesn’t have an Id) so it’s like :

document.getElementsByClassName("UgZKXd clearfix yYG3jf selected").item("")

is it correct to do so? does the className changes overtime? if so, any suggestions how should I implement this?
I am not a frontend developer so I couldn’t find the answer, thanks in advance!.

Not abble to use a map function on an array of dictionaries

Hope someone can help me out.

I am trying to dynamically create some cards on my webpage out of a dictionary.

I tried to create the function but the code inside the first

cards.map((character)=>(

is not recognizing the array of dictionaries.

Any ideias on how to fix it?


function MemoryCards() {
    const images = [
        "./img/Abadango.jpeg",
        "./img/abradolf.jpeg",
        "./img/Adjudicator.jpeg",
        "./img/AgencyDirector.jpeg",
        "./img/Alan.jpeg",
        "./img/Albert.jpeg",
        "./img/Alexander.jpeg",
        "./img/AlienMorty.jpeg",
        "./img/AlienRick.jpeg",
        "./img/Annie.jpeg",
        "./img/AntsJonson.jpeg",
        "./img/Beth.jpeg",
        "./img/Jerry.jpeg",
        "./img/morty.jpeg",
        "./img/ricky.jpeg",
        "./img/summer.jpeg"
    ]

    const cards = [];
    let len = images.length;

    for (let i = 0; i < len; i++) {
        let end = images[i].indexOf('.', 3);
        let name = images[i].substring(6, end);
        let card = { 'name': name, 'img': images[i], 'id': i };
        cards.push(card);
    }

    return (
        <div>
            cards.map((character)=>(
            <div class="card">
                <div className="card_header">
                    <img src={cards.img}></img>
                </div>
                <div className="card_body">
                    <h3>{cards.name}</h3>
                </div>

            </div>
            ))
        </div>

    )

}

export default MemoryCards;

how to set coordinates (x,y) for each id inside the tree

I have this array (of connections from ID to another):

const connectionsArr = [
  { sourceId: 1, targetId: 2 },
  { sourceId: 1, targetId: 9 },
  { sourceId: 9, targetId: 3 },
  { sourceId: 3, targetId: 5 },
  { sourceId: 3, targetId: 7 },
  { sourceId: 5, targetId: 6 },
  { sourceId: 6, targetId: 10 },
  { sourceId: 11, targetId: 12 }
];

From this array I created an array of “trees” with levels for each ID:

[
   {
      "id": 1,
      "children": [
         {
            "id": 2,
            "children": [],
            "level": 1
         },
         {
            "id": 9,
            "children": [
               {
                  "id": 3,
                  "children": [
                     {
                        "id": 5,
                        "children": [
                           {
                              "id": 6,
                              "children": [
                                 {
                                    "id": 10,
                                    "children": [],
                                    "level": 5
                                 }
                              ],
                              "level": 4
                           }
                        ],
                        "level": 3
                     },
                     {
                        "id": 7,
                        "children": [],
                        "level": 3
                     }
                  ],
                  "level": 2
               }
            ],
            "level": 1
         }
      ],
      "level": 0
   },
   {
      "id": 11,
      "children": [
         {
            "id": 12,
            "children": [],
            "level": 1
         }
      ],
      "level": 0
   }
] 

how can I set coordinates (x , y) for each id and the coordinates will be hierarchical,
and finally if I decide to put them on a picture / canvas is should look like this:

image description here

I don’t want to use an external library at all.

Thanks in advance to those who helped and will help .

PrivateRoute in React-router-dom v6 isnt working

I’m trying to use ProtectedRoute as
I can’t see why the code isn’t working, I’m not getting any error, but at /account it should display and its blank, I can see the header and footer, but the whole is missing
before trying to use a PrivateRoute, I could display Profile with any problem

my ProtectedRoute.js

 import React from "react";
    import { useSelector } from "react-redux";
    import { Navigate, Outlet } from "react-router-dom";

    const ProtectedRoute = () => {
    const {isAuthenticated} = useSelector((state)=>state.user)
    return isAuthenticated ? <Outlet /> : <Navigate to="/login"/>
    }

    export default ProtectedRoute;

my app.js

    function App() {

    const {isAuthenticated, user} = useSelector(state=>state.user)
    React.useEffect(() => {

    WebFont.load({
      google:{
        families: [ "Droid Sans", "Chilanka"],
      },
    });

    store.dispatch(loadUser())
    }, []);
  
    return (
    <Router>
      <Header/>
      {isAuthenticated && <UserOptions user={user} />}
      <Routes>
        <Route exact path="/" element={<Home/>}/>
        <Route exact path="/product/:id" element={<ProductDetails/>}/>
        <Route exact path="/products" element={<Products/>}/>
        <Route path="/products/:keyword" element={<Products/>}/>
        <Route exact path="/search" element={<Search/>}/>
        <Route exact path="/account" element={<ProtectedRoute/>}/>
          <Route exact path="/account" element={<Profile/>}/>
        <Route exact path="/login" element={<LoginSignUp/>}/>
      </Routes>
    <Footer/>
    </Router>
    );
   }

   export default App;

and my Profile

const Profile = () => {
 const { user, loading, isAuthenticated} = useSelector((state) => state.user);

 const navigate = useNavigate();

useEffect(() => {
    if(isAuthenticated === false){
        navigate("/login");
    }
}, [navigate,isAuthenticated])
return (
        <Fragment>
          <MetaData title={`${user.name}'s Profile`} />
          <div className="profileContainer">
            <div>
              <h1>My Profile</h1>
              <img src={user.avatar?.url} alt={user.name} />
              <Link to="/me/update">Edit Profile</Link>
            </div>
            <div>
              <div>
                <h4>Full Name</h4>
                <p>{user.name}</p>
              </div>
              <div>
                <h4>Email</h4>
                <p>{user.email}</p>
              </div>
              <div>
                <h4>Joined On</h4>
                <p>{String(user.createdAt).substr(0, 10)}</p>
              </div>                
              <div>
                <Link to="/orders">My Orders</Link>
                <Link to="/password/update">Change Password</Link>
              </div>
            </div>
          </div>
        </Fragment>
  );
};

export default Profile;

Chrome extension not loading after using SplitChunksPlugin in Webpack

I’m trying to reduce bundle weight of a Chrome extension / Firefox add-on built with React 17.0.2 + Webpack 5.7 + Typescript 4.3.5. This is how my webpack.common.js file looks like:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const manifestJson = require('./assets/manifest.json');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const BrowserExtensionWebpackPlugin = require('./tools/browser_extension_webpack_plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const distDir = (function () {
  switch (process.env.BROWSER) {
    case 'chrome':
      return 'dist_crx';
    case 'firefox':
      return 'dist_ff';
    default:
      throw new Error('BROWSER not supported');
  }
})();

module.exports = {
  entry: {
    main: './src/global/popup.js',
    background: './src/global/bg/index.js',
    local_backup_page: './src/global/page-local-backup/local_backup.tsx',
    page_options: './src/global/page-options/options.js',
    payment_cs: './src/global/cs/cs_payment.js',
    payment_inject: './src/global/inject/inject_payment.js',
    updatecard_cs: './src/global/cs/cs_updatecard.js',
    updatecard_inject: './src/global/inject/inject_updatecard.js',
  },
  output: {
    path: path.join(__dirname, distDir),
    filename: '[name].js',
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)?$/,
        exclude: /(node_modules)/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env', '@babel/preset-react'],
            },
          },
        ],
      },
      {
        test: /.(ts|tsx)$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /.scss$/,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
      },
      {
        test: /.css$/,
        // include: path.resolve(__dirname, 'src'),
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js', '.json'],
    alias: {
      ga: path.resolve(
        __dirname,
        process.env.BROWSER === 'firefox'
          ? './src/utils/lib/GoogleAnalytics/ga_mock.js'
          : './src/utils/lib/GoogleAnalytics/ga.js',
      ),
      '@': path.resolve(__dirname, 'src/'),
    },
    fallback: {
      http: false,
      https: false,
      assert: false,
      tls: false,
      fs: false,
      net: false,
    },
  },
  plugins: [
    // new MiniCssExtractPlugin({
    //   filename: 'tailwind.css',
    // }),
    new CleanWebpackPlugin({ cleanStaleWebpackAssets: false }),
    // new HtmlWebpackPlugin({ template: 'assets/html/main.html' }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'assets', 'html', 'main.html'),
      filename: 'main.html',
      chunks: ['main'],
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'assets', 'html', 'background.html'),
      filename: 'background.html',
      chunks: ['background'],
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'assets', 'html', 'options.html'),
      filename: 'options.html',
      chunks: ['page_options'],
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'assets', 'html', 'local_backup.html'),
      filename: 'local_backup.html',
      chunks: ['local_backup_page'],
    }),
    new NodePolyfillPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: 'assets',
          to: path.resolve(__dirname, distDir),
          // transform: function (content, filepath) {
          //   if (process.env.BROWSER !== 'firefox') return content;
          //   if (filepath.indexOf('manifest.json') === -1) return content;
          //   return content;
          //   // return ('' + content).replace(/s*"content_security_policy".*?n/g, 'n');
          // },
        },
      ],
    }),
    new webpack.DefinePlugin({
      __BROWSER__: JSON.stringify(process.env.BROWSER),
      __VERSION__: JSON.stringify(manifestJson.version),
    }),
    new BrowserExtensionWebpackPlugin({
      createManifestJson: ({}) => {
        if (process.env.BROWSER === 'firefox') {
          delete manifestJson.content_security_policy;
          delete manifestJson.key;
          delete manifestJson.oauth2;
          delete manifestJson.options_page;
          delete manifestJson.background.persistent;
          manifestJson.permissions = manifestJson.permissions.filter(
            (str) => str !== 'identity.email',
          );
        } else {
          delete manifestJson.applications;
        }

        return manifestJson;
      },
    }),
    new BundleAnalyzerPlugin({
      generateStatsFile: true,
    }),
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        antd: {
          test: /[\/]node_modules[\/]antd[\/]/,
          name: 'antd',
          chunks: 'all',
        },
        moment: {
          test: /[\/]node_modules[\/]moment[\/]/,
          name: 'moment',
          chunks: 'all',
        },
      },
    },
  },
};

Chunks are already been created for moment and antd, the extension is not loading though

blank extension

After checking on the page elements, root element in DOM looks empty:

html elements

I’ve been struggling a while with this and I’m not sure what could be causing this issue.

Can I run a script when are new folders in a root folder? [GOOGLE APPS SCRIPT]

I have a simple function in Google Apps Script that creates a series of subfolders and files inside a say so parentFolder:

function criaPastas() {
  const parentFolder = DriveApp.getFolderById("FOLDER-ID");
  const nameFolder = parentFolder.getName();
  const regExp = new RegExp(/(d+)/); // extract number
  const codigo = regExp.exec(nameFolder)[1];

  // Create folders
  const proprietarioFolder = parentFolder.createFolder(codigo + " - DOCUMENTOS PROPRIETÁRIO");

  // Create files
  const fichaDeImovel = DriveApp.getFileById("FILE-ID");
  const novaFichaDeImovel = fichaDeImovel.makeCopy("FICHA DE IMOVEL", proprietarioFolder);
}

The code works just fine. However, what I want to accomplish is:

  1. Run the script every 60s in the parentFolder (simple time trigger);
  2. IF there is a NEW folder inside the parentFolder, create the subfolder inside that. Something like:
    parentFolder > newSubFolder > automationCreatedFolder;
  3. ELSE do nothing;

I’m new to the Google Apps Script, so any help will be very appreciated!

Javascript Canvas Game that each time you die, the game gets faster, something is wrong? [closed]

So I am new to Javascript, I have been watching videos and have created a demo game from this.

It seems to mostly work ok, however when you die and hit Start Game again, the game starts but certain game objects now run at twice the speed, if you die again, the game gains speed yet again and does so for each death.

I have console.log() out a variety of variables, one was for “dt” my delta or change in time for the update(dt) function, on the second time through there seems to be 2 console logs for each dt, then i die a third time there are 3 console logs for each dt?

What am i not stopping or clearing?

Link to Game

Here is the link to the game where you can see the source with inspect.

Any help appreciated.

Oh also if you refresh the browser, everything gets sets back to normal?

How to enable a SharedRuntime Environment in a custom function excel add-in with a separate vuejs taskpane

What I need to do:

Create a shared runtime environment so that my excel custom functions can have access to the workbook information.

Current Setup:
The way the project seems to have been set up is, using the yeoman office generator to generate a custom function addin and then using vue-cli to generate a vue app to use as the taskpane.

Folder Structure:

RootFolder
Add-In 
    manifest.xml
    jest.config.js
    package.json
    tsconfig.json
    webpack.config.js
Taskpane
    package.json
    tsconfig.json
    vue.config.js

The Add-In folder holds the custom functions and the Taskpane folder holds the Vuejs app. I have left out other default files and added these because I believe they will help communicate my possible issue.

Steps To Merge:

I have edited Manifest.xml following the steps provided on Microsofts documentation.
Updated name to use SharedRuntime

<Set Name="SharedRuntime" MinVersion="1.1"/>

Added Runtimes tags within the Host tag

<Runtimes>
    <Runtime resid="Taskpane.Url" lifetime="long" />
</Runtimes>

Updated the Page tag to use Taskpane.Url

<Page>
    <SourceLocation resid="Taskpane.Url"/>
</Page>

Updated the FunctionFile tag with Taskpane.Url

<FunctionFile resid="Taskpane.Url"/>

In webpack.config.js:
I have removed the HtmlWebpackPlugin references and replaced with the following.

new HtmlWebpackPlugin({
filename: "index.html",
template: "../taskpane/public/index.html",
chunks: ["polyfill", "taskpane", "commands", "functions"]
})

Steps I did not provided in the Documentation:
Since the project was created using the yeoman office generator with the customfunctions option selected, I believe I needed to add the following to the webpack.config.js file’s entry object:

entry: {
    functions: "./src/functions/functions.ts",
    polyfill: "@babel/polyfill",
    commands: "./src/commands/commands.ts",
    taskpane: "../taskpane/src/main.ts"    <----- new addition

Problem:
When I try to build the project it throws errors such as:

ERROR in ../taskpane/src/main.ts
Module build failed
Error: TypeScript emitted no output for main.ts

Module not found errors

Property doesn’t exist errors

More Info:

I’m thinking (but would love to confirm) that the steps I took to create the shared runtime provided by the documentation are indeed correct, along with adding the taskpane file to the entry object in the webpack config. But I just can’t figure out why it won’t compile. I’m thinking it has to do with the different tsconfig.json configurations. The addin is using target: “es5” while taskpane is using target: “esnext”. There are other differences as well. If somebody can help me with this and needs that information, I will be more than happy to add it.

How to fetch Wikipedia site?Access to fetch at * from origin * has been blocked by CORS policy [duplicate]

I am tring to display website from wikipedia on my site but i have problem with cors.
Please can somone help me? I tried so many things but nothing work for me.

error:

Access to fetch at 'https://en.wikipedia.org/w/index.php?title=elon_musk&action=render' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

code:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>
   <div id="content"></div>
</body>
<script>
    contentUrl = 'https://en.wikipedia.org/w/index.php?title='
    afterContentUrl = '&action=render'
    title="elon_musk"

    let url = contentUrl + title + afterContentUrl
    fetch(url)
        .then(function (response) { return response.text(); })
        .then((data) => {
           console.log(data)
           document.getElementById('content').innerHTML = data
        })
    </script>
    </html>

https://www.mediawiki.org/wiki/API:Main_page

Thanks:)

React: How to have a onClick handler on parent affect children?

Originally I had a Parent Component which had this wrapper component on some DOM elements:

const Card = ({ }) => {

  const LinkComponent = ({ children }) =>
    to && !onClick ? (
      <Link aria-label={`${title} ${t('thumbnail-image')}`} to={to}>
        {children}
      </Link>
    ) : (
      <a aria-label={`${title} ${t('thumbnail-image')}`} href={href} onClick={onLinkClick}>
        {children}
      </a>
    );

  return (
    <CardArticle id={id} isListView={isListView} data-testid="card-article">
      {showThumbnail && (
        <LinkComponent>
          <CardImage
            id={id}
            alt={title}
            image={image}
            isLazyLoading={isLazyLoading}
            isListView={isListView}
          />
        </LinkComponent>
      )}
      <CardInfo>
        <TitleWrapper>
            <LinkComponent>
              <CardTitle data-testid="card-title" tabIndex={0} aria-label={title || t('untitled')}>
                {title}
              </CardTitle>
            </LinkComponent>
        </TitleWrapper>
    </CardArticle>
  );
};

What I want is instead of wrapping these elements with a component, I’d just like to pass a function to the onClick handler of the parent of the children.

const handleOnClick (e) => {
  if (to && !onClick) {
   return <Link aria-label={`${title} ${t('thumbnail-image')}`} to={to}>
           {xxxxxx} // what goes here?
          </Link>
  } else {
 return <a aria-label={`${title} ${t('thumbnail-image')}`} href={href} onClick={onLinkClick}>
        {xxxxxx} // what goes here?
       </a>
 }
}

  return (
    <CardArticle onClick={handleOnClick}>
    </CardArticle/>

I need to make the entire component a link instead of sections like it was!

Any help would be appreciated!

Show Button if get_the_term_list contains specific Text

I am trying to Show a BUTTON only if the wordpress post meta tag contains specific text.

strip_tags(get_the_term_list( $post->ID, ‘posttype’)

I have lot of tags in this posttypes tag for example- Hindi, English, Hindi-English, Maths, Hindi-Maths, Hindi-English-Maths.

I want to show this BUTTON for all posts if tag contains Hindi.

<button class="boxeedbk buttonbk">"CONTAINS HINDI as WELL"</button></a>

What statement could it be so I put in single.php worpdress theme.

Thank You

Display array containing Latex math notation

I am trying to display an array of math that contains Latex math notation- they are actually options on a drop-down menu or other types of questions. Below is the simplest example. Removing the ( ) for Latex, everything works fine.

options='[“( T+50 )”, “( 0.5T )”, “( 0.25n )”, “( 0.5n )”, “( T-0.5n )” ]’

(I have double backslashes they just aren’t showing..)

I would love to just skip the Latex altogether, but the math will get more complicated and Latex is a must.