Tronweb USDT20 Transfer FAILED -TRANSACTION REVERT>

Hello i want to transfer USDT with TRC20 by using tronWeb.I get the txid and everything but i somehow i cant trigger the smartcontract.So this is my code below:`const TronWeb = require(‘tronweb’);

// Create a TRON instance
const tronWeb = new TronWeb({
  fullHost: 'https://api.trongrid.io', // Use the TRON full node URL
});

// Function to send USDT TRC20 tokens
async function sendUsdt(addressTo, amount, privateKey) {
  try {
    // Convert the amount to SUN
    const amountSun = tronWeb.toSun(amount.toString());

    // Get the contract address of USDT TRC20 token
    const usdtContractAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; // USDT TRC20 contract address

    // Get the address associated with the private key
    const ownerAddress = tronWeb.address.fromPrivateKey(privateKey);

    // Create the transfer transaction data
    const transferData = await tronWeb.transactionBuilder.triggerSmartContract(
      usdtContractAddress,
      'transfer',
      {
        _to: addressTo,
        _value: amountSun
      },
      [],
      ownerAddress // Set the owner_address parameter
    );
    transferData.transaction.fee = fee;

    // Sign the transaction
    const signedTransaction = await tronWeb.trx.sign(
      transferData.transaction,
      privateKey
    );

    // Broadcast the transaction
    const receipt = await tronWeb.trx.sendRawTransaction(
      signedTransaction
    );

    console.log('Transaction receipt:', receipt);
  } catch (error) {
    console.error('Failed to send USDT:', error);
  }
}

// Usage: Call the sendUsdt function with the recipient's address, amount, and private key
const recipientAddress = 'TRECIPENT';
const amount = 10; // Amount of USDT to send
const privateKey = 'MY_PRIV_KEY'; // Set your private key here
const fee = 100000; // Fee value in SUN

sendUsdt(recipientAddress, amount, privateKey,fee);

`
And this is the output of the transaction : https://tronscan.org/#/transaction/e76d76d8898e7418cdb558573e90a3cc7b28e94da245df3990aa46f7d4fecc88
What should i try to avoid this? Thanks in advance.

Uncaught TypeError: Object prototype may only be an Object or null: undefined on promise

I am making some mock up for the company I work to, I am making an API call to send an XML file but the client throws Uncaught TypeError: Object prototype may only be an Object or null: undefined just before sending the request. I read that the imports are the problem but I can’t figure it out what, even because my company bought a very crappy tool to auto generate the server and client codes, the models, the api functions ecc ecc… but it sucks.

This is the call where the client fails:

upload() {
    console.log('mando richiesta 1');
    const fattura = this.delegates.parser.PostFile(this.file).toPromise().then((value) => {console.log(value)});
   console.log(fattura);
}

the this.delegates.parser.PostFile(x) is a function generated by the tool I mentioned before and I didn’t wrote it. It contains:

public PostFile(xmlFile: any) {
    return this.request<IPostFileResponse>('POST', 'PostFile', { xmlFile }, false);
}

the tool-generated request<T>(x) function:

protected request<TResponse>(method: 'DELETE' | 'GET' | 'HEAD' | 'JSONP' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH', resource: string, payload: any, disableContextAttach = false) {
    const url = this.api + resource;
    const options: IShHttpRequestBodyOptions<TResponse> = {};
    const serialized = this.serializer.serialize(payload);
    if (method.startsWith('P')) {
      options.headers = { 'Content-Type': 'application/json' };
      options.body = serialized;
    } else {
      if (typeof payload === 'object') {
        for (const key in payload) {
          const element = payload[key];
          if (isNoU(element)) {
            delete payload[key];
          }
        }
      }
      options.params = payload;
    }
    if (this.activity && this.activity.taskId && method !== 'JSONP') {
      options.headers = {
        'Content-Type': 'application/json',
        'Activity-TaskId': this.activity.taskId
      };
    }
    if (options) {
      options.observe = 'response' as 'body';
      options.responseType = 'text' as 'json';
    }
    let request: Observable<TResponse> = this.http.request<TResponse, any>(method, url, options)
      .pipe(map(x => this.deserialize.call(this, x)));
    if (!disableContextAttach) {
      if (payload) {
        this.attach(payload);
      }
      request = request.pipe(map(this.attach.bind(this)));
    }
    return request;
  }

and server side I have:

[HttpPost("postFile")]
// <custom:customAttributesPostFile>
// </custom:customAttributesPostFile>
public async Task<ActionResult<PostFileResponse>> PostFile([FromForm] PostFileRequest request, CancellationToken requestAborted)
{
  // <custom:PostFile>
  XmlSerializer ser = new XmlSerializer(typeof(FatturaElettronicaTypeDTO));
  Stream stream = (request.XmlFile as IFormFile).OpenReadStream();
  FatturaElettronicaTypeDTO deserialized = (FatturaElettronicaTypeDTO)ser.Deserialize(stream);

  _fatturaSelezionata.fatturaSelez = deserialized;

  var fatturaDto = _fatturaMapper.mapFattura(deserialized);

  return new PostFileResponse() { Fattura = fatturaDto }; /*fatturaDto*/
  // </custom:PostFile>
}

draggable overlay on touch screen in google map api

I used this gmap api code for building overlay div with image: http://jsfiddle.net/doktormolle/QRuW8/. it works for desktop with mouse, but not working with touch event. please, help me.

I tried to do it next:

google.maps.event.addDomListener(container,
‘touchstart’,
function(e){
this.style.cursor=’move’;
that.map.set(‘draggable’,false);
that.set(‘origin’,e);

        that.moveHandler  = google.maps.event.addDomListener(that.get('map').getDiv(),
            'touchmove',
            function(e){
                let touch = e.touches[0] || e.changedTouches[0];
                var origin = that.get('origin'),
                    left   = origin.clientX-touch.clientX,
                    top    = origin.clientY-touch.clientY,
                    pos    = that.getProjection()
                        .fromLatLngToDivPixel(that.get('position')),
                    latLng = that.getProjection()
                        .fromDivPixelToLatLng(new google.maps.Point(pos.x-left,
                            pos.y-top));
                that.set('origin',e);
                that.set('position',latLng);
                that.draw();
            });

    }
);

google.maps.event.addDomListener(container,'touchancel',function(e){
    that.map.set('draggable',true);
    this.style.cursor='default';
    google.maps.event.removeListener(that.moveHandler);
});

google.maps.event.addDomListener(container,'touchend',function(e){
    that.map.set('draggable',true);
    this.style.cursor='default';
    google.maps.event.removeListener(that.moveHandler);
});

but it doesn’t work. what do I make wrong? thanks

next js 404 when refresh dynamic route

I have error 404 not found when refresh page with dynamic routes ini next js, my structure page is like below:

pages
  [storeName]
     summaries.jsx
     [store-insight].jsx

when I’m in [store-insight].jsx I need the query in url to be used in hitting an api. for example www.url.com/storName/10, I use the 10 in an api body

here is the code in [store-insight].jsx:

  import { useRouter } from 'next/router';
  import { useEffect, useState } from 'react';
  import { BackButton } from '../../components/button/BackButton';
  import Navbar from '../../components/Navbar';
  import { useSelector } from 'react-redux';
  import { StoreInsightHeader } from '../../components/storeInsight/StoreInsightHeader';
  import { KeyValueInsight } from '../../components/storeInsight/KeyValueInsight';
  import { StoreInsightSummaryChart } from '../../components/storeInsight/StoreInsightSummaryChart';

  const StoreInsight = () => {
    const { back, query } = useRouter();
    const router = useRouter();

    const {
      store,
      filterReport,
      revenuInsight,
      featuresInsight,
      productInsight,
      browsingInsight,
      operationalGraph,
    } = useSelector((store) => store);
    // const { detailStore } = store;
    // const { name, country_code, location } = detailStore;

    const [storeDetail, setStoreDetail] = useState({});

    const storeDetails = () => {
      const splitted = query['store-insight']?.split('&');
      setStoreDetail((prev) => {
        return {
          ...prev,
          id: splitted[0],
          storeName: splitted[1],
          storeLocation: splitted[2],
          storeLogo: splitted[3],
        };
      });
    };

    useEffect(() => {
      if (query['store-insight']?.length > 0) storeDetails();
    }, [query, storeDetail?.id]);

    return (
      <>
        <div className='bg-white'>
          <Navbar storeLogo={storeDetail?.storeLogo} />
        </div>
        <div className='m-6 flex flex-1 flex-row items-center space-x-3'>
          <BackButton
            onClick={() => {
              router.push({
                pathname: `/${query?.storeName}/summaries`,
                query: { date: filterReport?.filter },
              });

              localStorage.removeItem('storeDetail');
            }}
            className={'h-3 w-3'}
          />
          <label className='text-[10px] font-bold'>
            Back to Account Level Insights
          </label>
        </div>
        <div className='bg-white p-4 rounded-lg mx-4'>
          <StoreInsightHeader
            storeName={`${storeDetail?.storeName} ${storeDetail?.storeLocation}`}
          />
          <KeyValueInsight />
          <StoreInsightSummaryChart />
        </div>
      </>
    );
  };

  export default StoreInsight;

also used in <KeyValueInsight /> component ini [store-insight].jsx page like below:

import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  setKeyInsight,
  setValueCreated,
} from '../../features/InsightV2/storeMetricSlice';
import { key_value_insight } from '../../resource/dummy-data';
import { getStoreMetric } from '../../services/insightV2/storeMetric';
import { KeyValueInsightCard } from '../card/KeyValueInsightCard';
import BrowsingInterestSkeleton from '../skeleton/BrowsingInterest';
import { convertInputPrice } from '../../helper/priceConverter';

export const KeyValueInsight = () => {
  const { query } = useRouter();
  const dispatch = useDispatch();
  const { store, filterReport, storeMetric } = useSelector((store) => store);
  const { filter, custom_date } = filterReport;
  const { key_insight, value_created } = storeMetric;

  const [loading, setLoading] = useState(false);
  const [storeDetail, setStoreDetail] = useState({});

  const storeDetails = () => {
    const splitted = query['store-insight']?.length && query['store-insight']?.split('&');

    setStoreDetail((prev) => {
      return {
        ...prev,
        id: splitted[0],
        storeName: splitted[1],
        storeLocation: splitted[2],
        storeLogo: splitted[3],
      };
    });
  };

  const currency = () => {
    if (storeDetail?.storeName === 'al-ikhsan') {
      return `MYR`;
    } else {
      return `SGD`;
    }
  };

  const fetchData = async () => {
    try {
      setLoading(true);
      if (filter === 'custom') {
        const { data } = await getStoreMetric({
          days: filter,
          storeId: storeDetail?.id,
          customStart: custom_date?.custom_start,
          customeEnd: custom_date?.custom_end,
        });

        if (data) {
          dispatch(setKeyInsight(data?.key_insight));
          dispatch(setValueCreated(data?.value_created));
        }
      } else {
        const { data } = await getStoreMetric({
          days: filter,
          storeId: storeDetail?.id,
        });

        if (data) {
          dispatch(setKeyInsight(data?.key_insight));
          dispatch(setValueCreated(data?.value_created));
        }
      }
    } catch (error) {
      console.log('store metric chart log <<<<<<', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (query['store-insight']?.length > 0) storeDetails();
  }, [query]);

  useEffect(() => {
    if (storeDetail?.id) fetchData();
  }, [storeDetail?.id, filter, custom_date]);

  return (
    <div className='grid grid-cols-2 mt-4 gap-x-4'>
      <div className='p-4 rounded-lg border'>
        <div className='font-semibold text-xs mb-4'>Key Insights</div>
        {loading ? (
          <BrowsingInterestSkeleton />
        ) : (
          <div className='grid text-center grid-cols-4 gap-x-4'>
            <KeyValueInsightCard
              title={'Capture'}
              value={key_insight?.capture?.value || 'WIP'}
            />
            <KeyValueInsightCard
              title={'Browsing'}
              value={key_insight?.browsing?.value || 'WIP'}
            />
            <KeyValueInsightCard
              title={'Leads'}
              value={key_insight?.leads?.value || 'WIP'}
            />
            <KeyValueInsightCard
              title={'Conversion'}
              value={key_insight?.conversion?.value || 'WIP'}
            />
          </div>
        )}
      </div>
      <div className='p-4 rounded-lg border'>
        <div className='font-semibold text-xs mb-4'>Value Created</div>
        {loading ? (
          <BrowsingInterestSkeleton />
        ) : (
          <div className='grid text-center grid-cols-4 gap-x-4'>
            <KeyValueInsightCard
              title={'Shoppers Served'}
              value={
                convertInputPrice(`${value_created?.shoppers_served?.value}`) ||
                'WIP'
              }
            />
            <KeyValueInsightCard
              title={'Time Saved'}
              value={
                convertInputPrice(`${value_created?.time_saved?.value}`) +
                ` min`
              }
            />
            <KeyValueInsightCard
              title={'Shoppers Acquired'}
              value={value_created?.shoppers_acquired?.value || 'WIP'}
            />
            <KeyValueInsightCard
              title={'Sales Generated'}
              value={
                `${currency()} ${parseFloat(
                  value_created?.sales_generated?.value,
                ).toFixed()}.00` || 'WIP'
              }
            />
          </div>
        )}
      </div>
    </div>
  );
};

How use Nuxt 3 with Express.js?

I have a legacy backend on Express.js and a frontend on Vue.js. I want to update the frontend to nuxt 3 and make it friends with Express.js, but the option of running the frontend and backend on 2 different ports does not suit me. Are there any options to implement Express in Nuxt on top of or instead of the standard server in Nuxt? Or maybe there are other options…

I tried the following but I get an error

nuxt.config:

serverHandlers: [
    { path: "/server-api*", handler: "~/server-api/app.js" },
],

/server-api/app.js:

import express from "express";
const app = express();

app.use(express.json());

app.get("/server-api/test", (req, res, next) => {
    res.send({
        message: "HELLO",
    });
});

export default fromNodeMiddleware(app)

app.vue for example:

<script>
export default {
  async setup() {
    const { data: message } = await useFetch("/server-api/test");
    return { message };
  },
};
</script>

Error:

[nuxt] [request error] [unhandled] [500] Cannot set properties of undefined (setting ‘content-type’)

How to add spaces and hyphens for credit cards?

How to add the Space and hyphens for credit cards as below
Credit Card – MasterCard
Social Security Number
American Ex
Credit Card – Visa
Credit Card – Diners Club
Credit Card – Discover

let me know to add space and as well the hyphens in different regex

Regex in JavaScript

How to use the value of an async function outside without using another async function or .then [duplicate]

context

I need to retrieve some data from an asynchronous function to use it in my normal synchronous code. That is, I need my application to wait for the response before proceeding without having to make the entire application asynchronous.

The problem

I’ve been looking at answers for 2 days and none of them explain how to do that. They all tell you that to work with asynchronous code, you must use promises or async/await. The problem is that a function marked as async always returns a promise, so it’s impossible to use the received value in your synchronous code. And the .then is still an asynchronous context. So what I’m finding is that if I want to use data retrieved by an async function throughout all my application, I have to convert half of the application to async. Otherwise, you always run the risk of asynchrony creating unwanted behavior.

The question

How do you wait for an asynchronous function to retrieve the data so you can use it normally in synchronous code? Is it possible to do that without stuffing all of this into another async function or a .then?

aditional info

Before marking this post as a duplicate, I must say that I have read about 20 similar messages ( like this one How do I return the response from an asynchronous call? ). In all of them, the solution they propose is to retrieve the information and use it in another async function or in a .then that is also async.

Run Javascript unit tests to test user input code in the application at run time

In many code learning sites, the application is able to test the code entered by user. Ex: freecodecamp.org runs unit tests to check if user has entered correct code. I am trying to get the same feature using angular as front end. I know that we can run tests from CLI using karma, but i want to run these tests when user inputs the code and show him if he as entered the expected code. I want to know how can it be done within the application.

Nodejs generating a azure sas url using generateBlobSASQueryParameters in @azure/storage-blob module

Hi I have a azure storage account where i will upload and create a sas url to download the image. below is the code that i used ,

const {
  BlobServiceClient,
  StorageSharedKeyCredential,
  BlobSASPermissions,
  generateBlobSASQueryParameters,
} = require("@azure/storage-blob");
const { ClientSecretCredential } = require("@azure/identity");


const clientCred = new ClientSecretCredential(process.env.STORAGE_TENANT,process.env.STORAGE_APPID,process.env.STORAGE_PASSWORD)

const blobServiceClient = new BlobServiceClient(
  `https://${process.env.STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
  clientCred
  
  );

  var blobName = "blobName";
    var containeName = process.env.PROFILE_UPLOAD_CONTAINER_NAME;
    const containerClient = blobServiceClient.getContainerClient(containeName);
    const blockBlobClient = containerClient.getBlockBlobClient(blobName);
    const response = await blockBlobClient.uploadData(image.data, {
      blobHTTPHeaders: {
        blobContentType: image.mimetype,
      },
    });
    if (response.etag) {
      const cerds = new StorageSharedKeyCredential(
        process.env.STORAGE_APPID,** ( earlier i used account name and key it worked perfectly fine)**
        process.env.STORAGE_PASSWORD
      );
      const date = new Date();
      const expires = new Date(
        Date.UTC(
          date.getFullYear() + 2,
          date.getMonth(),
          date.getDate(),
          23,
          59,
          59
        )
      );
  
      const sasToken = generateBlobSASQueryParameters(
        {
          containerName: containeName,
          blobName: blobName,
          expiresOn: expires,
          permissions: BlobSASPermissions.parse("racwd"),
        },
        **cerds** (i need to create cerds using tenantid,appid and password)
      ).toString();
      const sasUrl = blockBlobClient.url + "?" + sasToken;
      console.log("sasUrl", sasUrl);

I will not have account key. How to access the sasurl by using only tenantid,appid and password. Kindly guide

I am able to upload using tenantid,appid and password , but when i try to create a downloadable sasurl i am unable to do so, using the above tenantid,appid and password

Top 10 Acting Academy In Chandigarh?

MS Asian Film Academy offers the best Acting & Film making classes with an exciting way of learning to the aspiring actors, Editors, Writers , Directors and Filmmakers. It’s the best Academy for Acting, Editing, Direction, and Cinematography in India. We focus on the overall development of the students and Writing enhancing their skills by providing workshops online or offline. All the courses are Certified courses and it’s the one of the best Acting school in India (Chandigarh) with a stream of Bollywood most experienced and talented faculty who share their knowledge with the students.

MS Asian Film Academy offers the best Acting & Film making classes with an exciting way of learning to the aspiring actors, Editors, ,Writers , Directors and Filmmakers. It’s the best Academy for Acting, Editing, Direction Writing and Cinematography in India. We focus on the overall development of the students and enhancing their skills by providing workshops online or offline. All the courses are Certified courses and it’s the one of the best Acting school in India (Chandigarh) with a stream of Bollywood most experienced and talented faculty who share their knowledge with the students.

how to apply css on iframe code in css, javascript and jquery, html?

I’ve try this code for Iframe code css but it dosen’t working… can you suggest me how to apply css for iframe..

window.onload = function() { let myiFrame = document.getElementById("myiFrame"); let doc = myiFrame.contentDocument; doc.body.innerHTML = doc.body.innerHTML + '<style>.form_generater_form_div .block_label {font-weight: bold !important;}</style>'; }

OR

$("#myiFrame").on("load", function() { let head = $("#myiFrame").contents().find("head"); let css = '<style>.form_generater_form_div .block_label {font-weight: bold !important;}</style>'; $(head).append(css); });

Google Maps Javascript API is not showing up on webpage

I am trying to utilise a Google Map API on my React/Javascript code within the ‘Contact Us’ component of my website however the map itself is not showing up. I believe the code is working as the “Loading…” statement appears when the map is loading however when it has loaded in nothing is showing up.

Here’s my code in the ContactUs.js file:

import React from "react";
import contactuscss from "./ContactUs.module.css";
import Map from "./Map.js";

function ContactUs() {
  return (
    <div className={contactuscss.container}>
      <h2 className={contactuscss.contactus}>CONTACT US</h2>

      <div className={contactuscss.address}>
        <p>Unit 14 Parramatta Business Centre</p>
        <p>2 O'Connell Street</p>
        <p>Parramatta, NSW 2150</p>
        <p>Tel: +61 435 400 290</p>
      </div>

      <form>
        <div className={contactuscss.inputcontainer}>
          <input
            className={contactuscss.nameinput}
            type="text"
            id="name"
            name="name"
            placeholder="Name"
          />

          <input
            className={contactuscss.emailinput}
            type="text"
            id="email"
            name="email"
            placeholder="Email"
          />

          <input
            className={contactuscss.phoneinput}
            type="phone"
            id="phone"
            name="phone"
            placeholder="Phone"
          />

          <textarea
            className={contactuscss.textinput}
            id="message"
            name="message"
            rows="6"
            placeholder="Type your message here..."
          ></textarea>

          <button className={contactuscss.submitbutton} type="submit">
            Submit
          </button>
        </div>

        <div>
          <Map />
        </div>
      </form>
    </div>
  );
}

export default ContactUs;

And here’s the code in the Map.js file:

import React from "react";
import { GoogleMap, useLoadScript } from "@react-google-maps/api";

function Map() {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
  });

  if (!isLoaded) return <div>Loading...</div>;

  return (
    <GoogleMap
      zoom={10}
      center={{ lat: 44, lng: -80 }}
      mapContainerClassName={{ width: "100%", height: "100vh" }}
    ></GoogleMap>
  );
}

export default Map;

Here’s whats in my .env.local file:

NEXT_PUBLIC_GOOGLE_MAPS_API_KEY="AIzaSyCH4EPZrF5cvUmM9luEsNdOehQuRyJgAzk"

I’m not too sure what is wrong – I’ve also utilised the most up to date tutorial on youtube for how to upload this API on to my web page.

Google app scripts not replacing all text in a slide

I have a map of slide numbers with an array of associated variables.

const slidesMap = {
  0: ['firstName', 'date'],
  10: ['diversityScore', 'diversityDef', 'butyrateEfficiency', 'propionateEfficiency'],
  15: ['bacteria_1_three', 'bacteria_1_three_def', 'bacteria_2_three', 'bacteria_2_three_def', 'bacteria_3_three', 'bacteria_3_three_def'],
  16: ['bacteria_1', 'bacteria_1_def', 'bacteria_2', 'bacteria_2_def', 'bacteria_3', 'bacteria_3_def'],
  18: ['bacteria_10', 'bacteria_10_def', 'bacteria_11', 'bacteria_11_def', 'bacteria_12', 'bacteria_12_def', 'bacteria_13', 'bacteria_13_def','bacteria_14', 'bacteria_14_def', 'bacteria_15', 'bacteria_15_def'],
};

I have a map of variables generated from a spreadsheet,

const variablesMap = new Map();
 const generalValues = sheet.getRange('A1:B20').getValues();

  generalValues.forEach(row => {
    variablesMap.set(row[0], row[1]);
  });

Then I populate the necessary slides with necessary variables.

for (const page in slidesMap) {
    const variables = slidesMap[page];

    let newSlide = slides[page];

    let shapes = newSlide.getShapes();
    shapes.forEach(shape => {
      variables.forEach(variable => {
        shape.getText().replaceAllText(`{{${variable}}}`,variablesMap.get(variable), true);
      });
    }); 
  }

When I log the variables in the loop, I have everything I need both in variablesMap and in slides map. Also the page numbers are correct.

What I get, is half populated slides. For example on slide 15 4/6 variables are populated. {{bacteria_1_three_def}} and {{bacteria_3_three}} are still as placeholders.

What am I missing?

On slide 18 it’s even worse. all the ..._def are populated, but bacteria_... are as placeholders.

I am loosing my head.

I tried logging, everything seems correct.

My like button is not updating on the spot but is updating when I refresh the page, how can I fix it?

So I was changing some variable names when working on my website made using flask and after I was done changing the variable names, I found out that my like button is no longer working as intended. I click on it to like a post and then it does not update the like counter which is supposed to display the number of likes a post has. I refresh the page and the like counter is updated. It stays that way and shows that I have liked the post whenever I refresh the page too. I unlike the post and refresh it again, then it shows that the like has been removed, it does not update automatically. The tutorial I was following suggested to empty my cache and hard reload but that did not seem to work either. The whole thing was working fine before I changed the variable names so that might have something to do with it. The like button and counter exist inside the read route so I thought I should include that as well.
Here are the relevant routes in question:

@app.route('/read/<post_name>')
def read(post_name):
    posts = Image.query.filter_by(post_name=post_name)
    post1=Image.query.filter_by(post_name=post_name).first()
    post = Posts.query.filter_by(id=post1.post_id).first()
    author_id =Image.query.filter_by(post_name=post_name).first().user_id
    author = User.query.filter_by(id=author_id).first()
    return render_template('readmanga.html', posts=posts, post=post, post1=post1, user=current_user, author=author, post_name=post_name)

@app.route('/like-post/<post_id>', methods=["POST","GET"])
@login_required
def like(post_id):
    post = Posts.query.filter_by(id=post_id).first()
    like = Like.query.filter_by(author=current_user.id, post_id=post.id).first()
    if not post:
        return jsonify({'error':'Post does not exist.'}, 400)
    elif like:
        db.session.delete(like)
        db.session.commit()
    else:
        like = Like(author=current_user.id,
            post_id=post.id
            )
        db.session.add(like)
        db.session.commit()

    return jsonify({'likes':len(post.likes), 'liked':current_user.id in map(lambda x: x.author, post.likes)})

Here is the relevant database model:

class Posts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    # post_name = db.Column(db.String(50), nullable=False)
    likes = db.relationship('Like', backref='Posts', passive_deletes=True)
    date_created = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now(tz=datetime.timezone.utc))
    comments = db.relationship('Comment', backref='Posts', passive_deletes=True)

class Like(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id', ), nullable=False)

Here is the template:

      <div style="display: flex; flex-direction:column; justify-content: center; align-items: center; margin-top: 1.75%;">
            {% set post_id = post.id | string()  %}
            {% set link = "/like-post/"+post_id %}
            {% if user.id in post.likes|map(attribute="author")|list %}
                <i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: cornflowerblue" onclick="like('{{ post.id }}')"></i>
            {% else %}
            {% if user.id in post.likes|map(attribute="author")|list %}
                <i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: cornflowerblue" onclick="like('{{ post.id }}')"></i>
            {% else %}
                {% if current_user.is_authenticated %}
                    <i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: white" onclick="like('{{ post.id }}')"></i>
                {% else %}
                    <span id="message" style="font-family: sans-serif; font-weight: bold;"></span>
                    <i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: white" onclick="displayMessage('You need to log in to like posts.')"></i>
                {% endif %}
            {% endif %}
            {% endif %}
            <span id="likes-count-{{ post.post_id }}" style="font-family: sans-serif; font-weight: bold; color: white;">{{post.likes|length}}</span>
        </div>
    <script type="text/javascript" src="{{ url_for('static', filename='read.js') }}">

        </script>

Here is the javascript code:

function like(postID) {
    const likeCount = document.getElementById(`likes-count-${postID}`);
    const likeButton = document.getElementById(`likebtn-${postID}`);

    fetch(`/like-post/${postID}`, { method: "POST"})
    .then((res) => res.json())
    .then((data) => {
        console.log(data)
        likeCount.innerHTML = data['likes'];
        if (data['liked'] === true) {
            likeButton.style.color = 'cornflowerblue';
        } else {
            likeButton.style.color = 'white';
        }

    }).catch((e) => console.log(e));
}

Please help me as I am not able to find the error in this code and it is practically the same as my code before that was working, just with different variable dependencies.

How to get command line argument parameters in react?

How to get command line argument parameters in react?

I have a react code, built on Webpack. When I ran –

npm run build -- --configuration=dev

or

npm run build -- --configuration=qa

Based on that, I wanted to get the configuration parameters as DEV or QA – builds the web packs.

The problem here – How to get the npm params configuration, in the javascript?