Node JavaScript Heroku – CORS Works Successfully With All API calls Expect When Uploading Image API

Our web app has many apis that fetch from a node server deployed on heroku. All the apis work successfully except for one of the api which allow users to upload images to the node server. It worked fine in localhost but when we deployed it to production on heroku we are getting 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. We tried some of the suggestions on stackoverflow but none helped. CORS error only occurs with this particular api. All the other apis work just fine. Do cors have another approach or something when it comes to working with images?

***SERVER***
const express = require('express');
const bodyParser =  require('body-parser')
require('dotenv').config();
const https = require('https');
const port = process.env.PORT || 5000;
const app = express();
const cors = require('cors');

//Setting up the cors config
app.use(cors());


//Prevent application from crashing if incorrect route
app.all('*', (req, res, next) =>{
  const err = new Error(`Requested URL ${req.path} not found!`);
  err.statusCode = 404;
  next(err);
})

app.use((err, req, res, next) =>{
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: 0,
    message: err.message,
    stack: err.stack
  })
})


//Serve static files if in production
if(process.env.NODE_ENV === 'production'){

  //Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) =>{
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  });
}



app.listen(port, () => console.log(`Server started on port ${port}`));
***FRONTEND FETCH***
  let response = await fetch('"OUR HEROKU ROUTE"/uploadDesign',{
              method:'POST',
              body:JSON.stringify(data),
              headers:{
                'Content-Type':'application/json',
                'Accept':'application/json, text-plain */*'
              }
            })

How to make a pure-CSS animation of CLOCKWISE rotation past 359 degrees

I’m having an issue with pure CSS-based rotation using transform: rotate() coupled with transition: transform.

When rotating past 360 degrees, the transition causes a counter-clockwise rotation. See code below or on CodePen.

I know I can just keep increasing/decreasing the degree value (e.g. 356->360, instead for 359->0), but this is for a React app and I’d like to simply use defined “states” with related CSS classes (i.e. class “over-1” equals the three o’clock position, “over-2” equals six o’clock, etc.).

I thought about storing the rotation value in the React state and increasing/decreasing it based on the triggering events, but I would need to inject that style directly into the HTML. Additionally, the elements I’m transforming have more than just angle being applied. I would need to also code those values in the JavaScript (e.g. transform: "translate(-50%, -50%) rotate(" + this.state.rotation + "deg);") or else setting the transform property would overwrite the transform from the stylesheet (I think).

Also, I hate hardcoding style information in JavaScript.

I tried using a “transitional” process (CodePen) that (1) used a class to animate the rotation from 270 to 360 degrees, (2) wait until the animation finished, then (3) switch the rotation from 360 degrees to 0 degrees (without animation), then (4) set the “correct” class to 0 degrees with the transition property (so it wouldn’t be a one-off class assignment). The problem I had with this is that clicking the rotate button before the animation completed would interrupt the transition and show counter-clockwise rotation.

I found two other questions that were loosely related, but did not provide any answers.

<!DOCTYPE html>
<html>
    <head>
        <style>
            /* Button to trigger rotation */
            #control {
                position: absolute;
                top: 210px;
                left: 100px;
                transform: translate(-50%, 0)
            }
            /* Large, underlying disk */
            #under {
                position: absolute;
                top: 0;
                left: 0;
                background-color: blue;
                height: 200px;
                width: 200px;
                border-radius: 50%;
            }
            /* Smaller, rotating disk */
            #over {
                position: absolute;
                top: 100px;
                left: 100px;
                background-color: green;
                height: 100px;
                width: 100px;
                z-index: 1;
                border-radius: 50%;
            }
            /* Simple pointer to visually track rotation */
            #pointer {
                font-size: 50px;
                position: absolute;
                top: 0%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
            /* Rotate inner disk to point to the twelve o'clock position */
            .over-1 {
                transform: translate(-50%, -50%) rotate(0deg);
                transition: transform 0.5s;
            }
            /* Rotate inner disk to point to the three o'clock position */
            .over-2 {
                transform: translate(-50%, -50%) rotate(90deg);
                transition: transform 0.5s;
            }
            /* Rotate inner disk to point to the six o'clock position */
            .over-3 {
                transform: translate(-50%, -50%) rotate(180deg);
                transition: transform 0.5s;
            }
            /* Rotate inner disk to point to the nine o'clock position */
            .over-4 {
                transform: translate(-50%, -50%) rotate(270deg);
                transition: transform 0.5s;
            }
        </style>
        <script>
            this.position = 1;
            /* Rotate the disk clockwise to the next position */
            function rotate() {
                this.position += 1;
                if (this.position === 2) {
                    document.getElementById("over").classList.remove("over-1");
                    document.getElementById("over").classList.add("over-2");
                }
                if (this.position === 3) {
                    document.getElementById("over").classList.remove("over-2");
                    document.getElementById("over").classList.add("over-3");
                }
                if (this.position === 4) {
                    document.getElementById("over").classList.remove("over-3");
                    document.getElementById("over").classList.add("over-4");
                }
                /* PROBLEM: The transition from nine o'clock to twleve o'clock
                            causes the disk to rotate 270 degrees COUNTER CLOCKWISE */
                if (this.position === 5) {
                    document.getElementById("over").classList.remove("over-4");
                    document.getElementById("over").classList.add("over-1");
                    this.position = 1;
                }
            }
        </script>
    </head>
    <body>
        <div id="under"></div>
        <div id="over" class="over-1">
            <div id="pointer">^</div>
        </div>
        <div>
            <button id="control" onclick="rotate()">Rotate</button>
        </div>
    </body>
</html>

Why is data1 null?

For some reason data1 is reading as null why is this

.addUserOption(option =>
              option
          .setName('groupmember')
        .setDescription('Group member you would like to kick')
          .setRequired(true))),
const mention  = interaction.options.getUser('groupmember')
     const data1 = await ingroups.findOne({User:mention.id})
     console.log(mention.id)
     if(data1.GroupName !== user.GroupName){
         return await interaction.reply('The person you are attempting to kick is not in your group.')
     }```

How to split and regex at specific word

Hi guys i know its a common question but i cant figure out how to use regex to do this

I have this string

http://localhost:3002/website/site1=mysite.xyz&site2=mysecondsite.xyz

and i want to split when there is “site[1 or 2]=” so it would return me always [“mysite.xyz”, “mysecondsite.xyz”]

Even in this situation

http://localhost:3002/website/site1=mysite.xyz&start_at=2022-07-06&end_at=2022-07-06&site2=mysecondsite.xyz&start_at2=2022-07-06&end_at2=2022-07-06

it must return me [“mysite.xyz”, “mysecondsite.xyz”]

So for this i thought about using regex with split, did this but ofc it doesnt work window.location.pathname.split(/site=/);

If regex doesnt works on 2 words dynamically like i’m looking for. I can run the split function two times like

window.location.pathname.split(/site1=/);
window.location.pathname.split(/site2=/);

but it doesnt returns me only the website elements ["mysite.xyz"] and [“mysecondsite.xyz”]

In clear i want to do something this

mystring.split(get only site string after the equals and only that)

Thanks !

React: Deleting dynamically added row removes every rows below it

I have a program to add/delete rows of a component dynamically.

Row Component

The row component is as shown below.

enter image description here

-----
component row
-----

import Select from "react-select";
import { Row, Col, Button, Container, Form } from "react-bootstrap";
import React, { useState } from "react";
import { useEffect } from "react";

const baseurl = "http://192.168.121.10:5000/api";
const Dselect = (props) => {
  const [pdtCodeOptions, setPdtCodeOptions] = useState([]);
  const [catListOptions, setCatListOptions] = useState([]);
  const [pdtListOptions, setPdtListOptions] = useState([]);

  const [selectedCat, setSelectedCategory] = useState();
  const [selectedPcode, setSelectedPCode] = useState();
  const [selectedPName, setSelectedPName] = useState();

  useEffect(() => {
    const fetchCat = async (e) => {
      const res = await fetch(`${baseurl}/cat`);
      const cList = await res.json();

      let catOpt = [];
      for (let i = 0; i < cList.length; i++) {
        catOpt.push({ label: cList[i].category, value: cList[i].category });
      }
      setCatListOptions(catOpt);
    };

    const fetchPdtCode = async (e) => {
      const res = await fetch(`${baseurl}/pdtlist`);
      const pList = await res.json();
      const pdtList = [];
      for (let i = 0; i < pList.length; i++) {
        pdtList.push({ label: pList[i].pdt_id, value: pList[i].pdt_id });
      }
      setPdtCodeOptions(pdtList);
    };

    fetchCat();
    fetchPdtCode();
  }, []);

  const getPdtDetails = async (e) => {
    const pdtID = e.value;

    const res = await fetch(`${baseurl}/details`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: pdtID }),
    });
    const detList = await res.json();

    const pdt_name = detList[0].pdt_name;
    const category = detList[0].category;

    setSelectedCategory({ label: category, value: category });
    setSelectedPName({ label: pdt_name, value: pdt_name });
  };

  const updateList = async (e) => {
    const catVal = e.value;
    console.log(e);

    const res = await fetch(`${baseurl}/pdtList`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: catVal }),
    });
    const pdtList = await res.json();

    const catPdtList = [];
    for (let i = 0; i < pdtList.length; i++) {
      catPdtList.push({
        label: pdtList[i].pdt_name,
        value: pdtList[i].pdt_name,
      });
    }
    setPdtListOptions(catPdtList);
  };

  const getPdtcode = async (e) => {
    /* ? * here, i want to get the category value also */
    const pdtVal = e.value;

    const res = await fetch(`${baseurl}/pdtCode`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ data: pdtVal }),
    });
    const code = await res.json();
    console.log(code);
    setSelectedPCode(code);
  };

  return (
    <Row className="mt-3">
      <Col lg={3} md={3} xs={3}>
        <Select
          options={pdtCodeOptions}
          placeholder="Select product"
          value={selectedPcode}
          onChange={(e) => {
            console.log({ selectedPcode });
            setSelectedPCode(selectedPcode);
            getPdtDetails(e);
          }}
        />
      </Col>

      <Col lg={3} md={3} xs={3}>
        <Select
          options={catListOptions}
          placeholder="Category"
          value={selectedCat}
          onChange={(e) => {
            setSelectedCategory(selectedCat);
            updateList(e);
          }}
        />
      </Col>
      <Col lg={3} md={3} xs={3}>
        <Select
          options={pdtListOptions}
          onChange={(e) => {
            setSelectedPName(selectedPName);
            getPdtcode(e);
          }}
          value={selectedPName}
          placeholder="Select product"
        />
      </Col>
      <Col lg={2} md={2} xs={2}>
        <Button
          type="button"
          onClick={(e) => props.onDelete(props.r)}
          className="btn btn-secondary"
        >
          Del
        </Button>
      </Col>
    </Row>
  );
};

export default Dselect;

This is the code where rows of this component are added upon button click.

import React from "react";
import Dselect from "../components/dSelect";
import { Row, Col, Form, Button } from "react-bootstrap";
import { useState, useEffect } from "react";

const TableShow = () => {
  const [row, setRow] = useState([<Dselect key="0" r="0" />]);

  const addRow = () => {
    let prevKey = row.slice(-1)[0].key;
    let thisKey = parseInt(prevKey) + 1;

    setRow([...row, <Dselect onDelete={delRow} key={thisKey} r={thisKey} />]);
  };

  const delRow = (index) => {
    const data = [...row];
    console.log(data);
    data.splice(index, 2);
    console.log(data);
    setRow(data);
  };

  return (
    <div>
      <Button onClick={addRow}>Add</Button>
      <Form>{row}</Form>
    </div>
  );
};

export default TableShow;

When clicking the delete button, every rows below the clicked one is also getting deleted.

Issue

![enter image description here
➡
enter image description here

I could figure out that the “…row” value inside delRow function is fetching only those values upto the clicked index. Can anyone help to correct the mistake in this code?

How to use columnDef.targets when wanting to pull specific columns from the database and putting into an array

ref

e.g i need to pull the column from empid – mname

$(document).ready(function() {
  $('#empList').DataTable({
    'fnCreatedRow': function(nRow, aData, iDataIndex) {
      $(nRow).attr('empid', aData[0]);
    },
    'serverSide': 'true',
    'processing': 'true',
    'paging': 'true',
    'order': [],
    'ajax': {
      'url': 'fetch_emp.php',
      'type': 'post',
    },
    "aoColumnDefs": [{
        "bSortable": false,
        "aTargets": [0,4]
      },

    ]
  });
});

I tried to change the target to “_all” string but still gets error

How do I filter out spam inputs on an HTML form?

I am making a portfolio website with React and at the bottom of the site I have a basic contact form. However, I have no way to filter out bots from flooding my inbox with spam messages. What is a simple way to prevent this? It is the same name every time, so even if there is a way to prevent certain words from providing submissions that would work as well.
Image of Form.

How to create a horizontally scrolling data table using datatables.js

I am attempting to format my table using DataTables, however I can’t seem to get it working properly. I searched stack overflow, youtube, and the DataTables website for solutions and I have tried everything that I have found but still haven’t gotten the result I’m looking for, particularly a horizontal scroll bar. I am very new to html and javascript so any help would be much appreciated.

Here are some of the changes I have tried, but there are many more I cannot remember.

  1. using scrollX: true instead of “sScrollX” : “100%
  2. setting the style tag of the table to style=”overflow-x:auto;”
  3. Removing the divs before the table

Here is what my code currently looks like:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>


    <script type="text/javascript">
        $(document).ready(function () {
            $('#recon-table').DataTable({
                "sScrollX": "100%",
                "sScrollXInner": "110%"
            });
        });
    </script>

<html>
<head>
    <title>Recon Table</title>
</head>
<body>
    <div class="box-transparent">
        <div class="box-content table-scroll-box">
            <table class="display nowrap" id="recon-table" style="width:100%">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Phone Number</th>
                        <th>Username</th>
                        <th>Date of Birth</th>
                        <th>Language</th>
                        <th>Gender</th>                        
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>John</td>
                        <td>Doe</td>
                        <td>[email protected]</td>
                        <td>1234567890</td>
                        <td>uname</td>
                        <td>English</td>
                        <td>Male</td>                            
                    </tr>                    
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

Trying to build a tree but having issues. Please help =)

I found a really cool collapsible tree here https://bl.ocks.org/mbostock/4339083. He is using a nested .json file as his data. I had to convert my flat .json data into a nested .json data but mine is stored inside a variable string “rootString” rather than an actual .json file.

Formatting my json to have children and parentIDs

My flat json didn’t have children only parent nodes. So i had to do some mapping then all children to each node. To see that it worked how expected I did:

console.log(JSON.stringify(rootString, undefined, 4));

console.log output

Now, i’ve tried taking the code from the collapsible tree to try adding my own data to it, but I’ve run into an issue here:

Current issue

I’m new to Javascript and D3 and found out this is called an anonymous function, but i’m not sure what this error is for? Please help =)

get a list of properties from a javascript object [duplicate]

I have something like this:

{
  "id": 15,
  "author": "harry",
  "text": "Hi everybody!",
  "timestamp": "Jul 05 2022, 02:02 PM",
  "likes": [
    {
      "id": 3,
      "username": "ron",
      "followers": [
        "harry",
        "giuliano"
      ],
      "following": [
        "giuliano",
        "harry"
      ]
    },
    {
      "id": 3,
      "username": "hermione",
      "followers": [
        "harry",
        "giuliano"
      ],
      "following": [
        "giuliano",
        "harry"
      ]
    }
  ],
  "likes_number": 1
}

I nee to check if a username is in the object followers. How do I get a list of the usernames of the followers (ron and hermione) in javascript?

Adsense Apps Script Row quota exceeded

I’ve been stuck with a script that will pull data from AdSense & store it into google Sheets and append new results.

If you have a sample code please share it with me.
My current code & Error I’m getting: “GoogleJsonResponseException: API call to adsense.accounts.reports.generate failed with error: Report row quota exceeded” attached
enter image description here

function generateReport(accountName, adClientReportingDimensionId) {
  // Prepare report.
  const today = new Date();
  const jan2015 = new Date(2010, 0);
  // const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);

  // const report = AdSense.Accounts.Reports.generate(                     )
  const report = AdSense.Accounts.Reports.generate(accontNameId, {
    // Specify the desired ad client using a filter.
    filters: ['AD_CLIENT_ID==' + escapeFilterParameter(adClientReportingDimensionId)],
    metrics: ['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE', 'CLICKS',
      'AD_REQUESTS_CTR', 'COST_PER_CLICK', 'AD_REQUESTS_RPM',
      'ESTIMATED_EARNINGS', 'IMPRESSIONS', 'IMPRESSIONS_RPM'],
    dimensions: ['DATE', 'COUNTRY_NAME'],
    // dimensions: ['COUNTRY'],
    // ...dateToJson('startDate', oneWeekAgo),
    ...dateToJson('startDate', jan2015),
    ...dateToJson('endDate', today),                        
    // Sort by ascending date.
    orderBy: ['+DATE'],
  });

Logger.log(report)
  if (!report.rows) {
    Logger.log('No rows returned.');
    // return;
  }
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = spreadsheet.getSheetByName('AdSenseReport_subrin')
  // Append the headers.
  var textFinder = sheet.getRange('A2:Z2').createTextFinder('DATE');

     var firstOccurrence = textFinder.findNext();
  if (!firstOccurrence) sheet.appendRow(report.headers.map((header) => header.name));

  // Append the results.
  if (report.rows) {

  sheet.getRange(2, 1, report.rows.length, report.headers.length)
      .setValues(report.rows.map((row) => row.cells.map((cell) => cell.value)));

  Logger.log('Report spreadsheet created: %s',
      spreadsheet.getUrl());
  }
}

Typescript passing an array as parameters (call method) TS2345

Sample code

let dolphinScores1 = [2,2,2] 
const average = (a:any,b:any,c:any) => (a+b+c)/3 ;
console.log(average.apply(this,dolphinScores1));  //Quokka output: 2

Type script gives an error of:

Argument of type 'number[]' is not assignable to parameter of type '[a: any, b: any, c: any]'.
Target requires 3 element(s) but source may have fewer.ts(2345)

is there a way to fix this in TS? in js it works fine.